代码如下:
#include <iostream>
using namespace std;
class A {
static int id_;
public:
static void setId(int id) {
id_ = id;
}
static int getId() {
return id_;
}
};
int main()
{
A::setId(10);
cout << A::getId() << endl;
return 0;
}
当我在Xcode、Mac OS中编译它时,会出现一条错误消息:
Undefined symbols for architecture x86_64:
"A::id_", referenced from:
A::setId(int) in main.o
A::getId() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
如果我添加该行:
int A::id_ = 10;
之前main()
。然后,一切都很好。这是什么原因?