3

有以下程序:

#include <iostream>
#include <string>

using namespace std;

class Record
{
public:
    static Record* GetInstance(string name);
void printName();
private:
Record(string name);
string name_;
static Record *record;
};

Record::Record(string name)
:name_(name)
{
}

Record*
Record::GetInstance(string name)
{
if(record == NULL) {
    record = new Record(name);
}
return record;
}

void
Record::printName()
{
cout << name_ << endl;
}

int main()
{
Record* record1 = Record::GetInstance("sellers");
record1->printName();
Record* record2 = Record::GetInstance("customers");
record2->printName();   
}

我正在编译和链接:
g++ -g -c -Wall main.cpp
g++ -g -Wall main.o -o main

编译完成且没有错误(第一个命令)。但是链接给出了这个错误:

Undefined                       first referenced    
 symbol                             in file    
Record::record                      main.o    
ld: fatal: Symbol referencing errors. No output written to main    
collect2: ld returned 1 exit status    

想知道如何纠正这个问题。

4

1 回答 1

2

您需要在某处定义变量,即

Record *Record::record;
于 2012-12-14T23:10:25.870 回答