本文介紹了在 C++ 中訪問靜態(tài)類變量?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
重復(fù):
C++:對靜態(tài)類成員的未定義引用
Duplicate:
C++: undefined reference to static class member
如果我有這樣的類/結(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;
}
這不起作用.我收到對‘Foo::bar’的未定義引用"錯誤.如何在 C++ 中訪問靜態(tài)類變量?
This doesn't work. I get an "undefined reference to `Foo::bar'" error. How do I access static class variables in C++?
推薦答案
您必須在實現(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++ 中訪問靜態(tài)類變量?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!