Xcode中的C ++ Singleton

时间:2012-01-25 01:45:56

标签: c++ xcode singleton

我正在尝试使用Xcode在C ++中创建一个Singleton类。这是一个非常基础的类,我得到一个我不理解的链接器错误。可以帮忙吗?

这是类头文件:

#ifndef _NETWORK_H_
#define _NETWORK_H_

#include <iostream>
#include <list>
#include "Module.h"

using namespace std;

/*
 * Assume only one network can run at a time 
 * in the program. So make the class a singleton.
 */
class Network {
private:
    static Network* _instance;
    list<Module*> _network;

public:
    static Network* instance();
};

#endif

这是impl文件:

#include "Network.h"

Network* Network::instance() {
    if (!_instance)
        _instance = new Network();
    return _instance;
}

以下是编译器错误:

Undefined symbols for architecture x86_64:
  "Network::_instance", referenced from:
      Network::instance() in Network.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

2 个答案:

答案 0 :(得分:6)

您需要在某处为Network::_instance声明实际存储空间。可能是impl。文件。

尝试添加到您的impl文件:

Network *Network::_instance=0;

答案 1 :(得分:4)

您需要在实现文件中定义您的实例:

#include "Network.h"

Network *Network::_instance;

static Network *_instance;声明只是说某个地方存在Network::_instance。您必须在某处提供单一定义才能实际存在。