本文介紹了在 C++ 中訪問(wèn)靜態(tài)類(lèi)變量?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
重復(fù):
C++:對(duì)靜態(tài)類(lèi)成員的未定義引用
Duplicate:
C++: undefined reference to static class member
如果我有這樣的類(lèi)/結(jié)構(gòu)
If I have a class/struct like this
// header file
class Foo
{
public:
static int bar;
int baz;
int adder();
};
// implementation
int Foo::adder()
{
return baz + bar;
}
這不起作用.我收到對(duì)‘Foo::bar’的未定義引用"錯(cuò)誤.如何在 C++ 中訪問(wèn)靜態(tài)類(lèi)變量?
This doesn't work. I get an "undefined reference to `Foo::bar'" error. How do I access static class variables in C++?
推薦答案
您必須在實(shí)現(xiàn)文件中添加以下行:
You must add the following line in the implementation file:
int Foo::bar = you_initial_value_here;
這是必需的,以便編譯器為靜態(tài)變量留出空間.
This is required so the compiler has a place for the static variable.
這篇關(guān)于在 C++ 中訪問(wèn)靜態(tài)類(lèi)變量?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!