2012-12-14 41 views
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主要是

編譯完成沒有錯誤(第1條命令)。但鏈接是給這個錯誤:

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  

想知道如何解決這個問題。

回答

2

您需要的地方定義變量,即

Record *Record::record; 
+1

+1某處類的範圍,但類定義之後。 – Mahesh

+0

謝謝。這解決了它。 – Romonov