未定义的引用错误消息 - C ++

时间:2009-07-14 01:27:10

标签: c++ linker

  

可能重复:
  Undefined reference - C++ linker error

现在,我在这些语句中分别收到了“GlobalClass :: s_instance”和“GlobalClass :: instance()”的未定义引用错误消息:

GlobalClass *GlobalClass::s_instance = 0;

GlobalClass::instance()->set_value(myAddress);  \\ <== undefined reference    
std::cout << "====>address is is " << GlobalClass::instance()->get_value() 

有什么想法吗?代码如下所示:

=============================================== =

#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; \\ <== undefined reference 


    std::string myAddress = "abc";
    GlobalClass::instance()->set_value(myAddress);  \\ <== undefined reference

    std::cout << "====>address is is " << GlobalClass::instance()->get_value() 
    \\ <== undefined reference

                 << std::endl;
    return 0;

}

2 个答案:

答案 0 :(得分:2)

在您的CPP文件中,移动“Global :: s_instance = 0;”在main()之外,并以静态为前缀,例如

static Global::s_instance = 0;
int main()
{
...
}

答案 1 :(得分:2)

继Alex Black的回复之后,它抱怨GlobalClass :: instance()函数没有实现。它没有:

static GlobalClass *instance() {
        if (!s_instance)
                s_instance = new GlobalClass;
        return s_instance;
    }

真的应该是:

GlobalClass *GlobalClass::instance() {
            if (!s_instance)
                    s_instance = new GlobalClass;
            return s_instance;
        }

不要忘记即使它是静态的,它仍然是一个成员函数!