2013-03-24 153 views
-1

我試圖端口這個Java單例類C++:C++鏈接錯誤未定義參考

public class Singleton { 
private static Singleton uniqueInstance; 

private Singleton() {} 
public static Singleton getInstance() { 
    if (uniqueInstance == null) { 
     uniqueInstance = new Singleton(); 
    } 
     return uniqueInstance; 
    } 
} 

我移植到這個C++代碼:

class Singleton { 
private: 
    Singleton() { 
    cout << "new Singleton is called" << endl; 
    } 
    static Singleton* uniqueInstance; 
public: 
    static Singleton* getInstance() { 
    if (!uniqueInstance) { 
     uniqueInstance = new Singleton(); 
    } 
    return uniqueInstance; 
    } 
}; 

但我不能編譯這個!和gcc鏈接器錯誤發生。

+1

請準確顯示鏈接器錯誤是什麼。 – seand 2013-03-24 08:04:00

回答

5

確保您定義的static成員的聲明外:

Singleton* Singleton::uniqueInstance = nullptr; 
+3

你也應該初始化爲nullptr。 – 2013-03-24 08:59:34

+0

@AlexChamberlain爲什麼?我的程序在沒有使用nullptr的情況下沒有錯誤地編譯! – 2013-03-24 09:59:12

+1

@Khajavi還沒有高度優化?指針在初始化時不保證爲零。 – 2013-03-24 18:10:04

2

你的CPP文件可能不爲靜態實例預留空間,則需要添加 Singelton* Singleton::uniqueInstance = NULL;到您的CPP文件,然後將它分配第一個電話