1

我的代码是:

class cMySingleton{
private:
    static bool bInstantiated;
    int mInt;
    cMySingleton(){
        mInt=0;
    }
public:
    cMySingleton(int c){
        if (bInstantiated){
            cout << "you can only instantiated once";
        }
        else {
            cMySingleton();
            mInt=c;
        }
    }
};

int main () {

    cMySingleton s(5);
    cMySingleton t(6);
}

链接器不断抱怨:

Undefined symbols for architecture x86_64:
  "cMySingleton::bInstantiated", referenced from:
      cMySingleton::cMySingleton(int) 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)

到底是怎么回事?C++新手来了~~

4

3 回答 3

3

你应该初始化静态字段。

http://ideone.com/Y1huV

#include <iostream>
class cMySingleton{
private:
    static bool bInstantiated;
    int mInt;
    cMySingleton(){
        mInt=0;
    }
public:
    cMySingleton(int c){
        if (bInstantiated){
            std::cout << "you can only instantiated once";
        }
        else {
            cMySingleton();
            mInt=c;
        }
    }
};
bool cMySingleton::bInstantiated = true;
int main () {

    cMySingleton s(5);
    cMySingleton t(6);
}

您可以在这里找到更多信息:

静态数据成员初始化

cout 周围还缺少 include 和 std::。

于 2012-09-11T06:39:20.563 回答
2

初始化

static bool bInstantiated;

在外面cMySingleton

bool CMySingleton::bInstantiated;
于 2012-09-11T06:37:02.693 回答
2

不要忘记在 .cpp 文件中的类声明之外初始化静态成员:

bool cMySingleton::bInstantiated = false;
于 2012-09-11T06:40:33.253 回答