错误消息"undefined reference to 'List::a'"



我在链接代码时会收到下面显示的错误。我该如何解决此问题?

看来静态变量没有初始化。

#include <iostream>
#include <cstdlib>
using namespace std;
struct name{
    char c;
};
class List {
    static name *a;
public:
    static void modify()
    {
        a = new name();
        cout<<"yes";
    }
};
name List::*a = NULL;
int main()
{
    List::modify();
}
g++ O3 -Wall -c -fmessage-length=0 -o sample.o "..\sample.cpp"
g++ -o sample.exe sample.o
sample.o:sample.cpp:(.text.startup+0x35): undefined reference to `List::a'
collect2.exe: error: ld returned 1 exit status

name List::*a = NULL;不做您预期的事情。它定义了一个名为a的全局变量,该变量是指向name类型List的非静态成员的指针。

List::a的定义应为

name* List::a = NULL;

最新更新