【发布时间】:2012-10-29 16:23:50
【问题描述】:
可能重复:
undefined reference to static member variable
What is an undefined reference/unresolved external symbol error and how do I fix it?
#include<iostream>
using namespace std;
class abc {
private:
static int a ;
public:
abc(int x) {
a = x;
}
void showData() {
cout<<"A = "<<a<<endl;
}
};
int main() {
abc a1(4);
abc a2(5);
a1.showData();
a2.showData();
return 0;
}
当我尝试在 Ubuntu 上使用 GCC 编译器编译这个函数时。我收到以下错误。
/tmp/ccCKK2YN.o: In function `main':
static1.cpp:(.text+0xb): undefined reference to `Something::s_nValue'
static1.cpp:(.text+0x14): undefined reference to `Something::s_nValue'
collect2: ld returned 1 exit status
Compilation failed.
以下代码运行良好
#include<iostream>
using namespace std;
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
int main()
{
Something cFirst;
cFirst.s_nValue = 2;
Something cSecond;
std::cout << cSecond.s_nValue;
return 0;
}
这是因为静态成员变量在通过对象访问它们之前需要显式初始化。为什么会这样?
【问题讨论】:
-
参见stackoverflow.com/questions/12573816/… - 更具体地说,“静态数据成员必须在单个翻译单元中的类外部定义”
标签: c++ gcc ubuntu static-members