我在这个声明中收到一条未定义的引用错误消息:
GlobalClass *GlobalClass::s_instance = 0;
有任何想法吗?代码如下所示:
================================================
#ifndef GLOBALCLASS_H_
#define GLOBALCLASS_H_
#include <string>
class GlobalClass {
public:
std::string get_value();
void set_value(std::string);
static GlobalClass *instance();
static GlobalClass *s_instance;
private:
std::string m_value;
};
#endif /* GLOBALCLASS_H_ */
===============================================
#include <string>
#include "GlobalClass.h"
/*
GlobalClass(int v = 0)
{
m_value = v;
}
*/
static GlobalClass *s_instance;
std::string GlobalClass::get_value()
{
return m_value;
}
void GlobalClass::set_value(std::string v)
{
m_value = v;
}
static GlobalClass *instance() {
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
================================================== =========
#include <iostream>
#include "GlobalClass.h"
using namespace std;
int main() {
GlobalClass::s_instance = 0;
std::string myAddress = "abc";
GlobalClass::instance()->set_value(myAddress); \\ <=== compiler error
std::cout << "====>address is is " << GlobalClass::instance()->get_value()
<< std::endl;
return 0;
}
解决方法:
您是否尝试实施Singleton类? IE浏览器.您只需要该类的一个实例,并且您希望该实例可供包含该类的任何人使用.我认为它通常称为Singleton,下面的示例按预期工作:
Singleton.h:
#include <string>
class Singleton
{
public:
static Singleton* instance()
{
if ( p_theInstance == 0 )
p_theInstance = new Singleton;
return p_theInstance;
}
void setMember( const std::string& some_string )
{
some_member = some_string;
}
const std::string& get_member() const
{
return some_member;
}
private:
Singleton() {}
static Singleton* p_theInstance;
std::string some_member;
};
Singleton.cpp:
Singleton* Singleton::p_theInstance = 0;
main.cpp中:
#include <string>
#include <iostream>
#include "Singleton.h"
int main()
{
std::string some_string = "Singleton class";
Singleton::instance()->setMember(some_string);
std::cout << Singleton::instance()->get_member() << "\n";
}
请注意,构造函数是私有的,我们不希望任何人创建我们的单例实例,除非它通过’instance()’运算符.