Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c+中的单态+;编译错误_C++_Singleton - Fatal编程技术网

C++ c+中的单态+;编译错误

C++ c+中的单态+;编译错误,c++,singleton,C++,Singleton,我试着用C编写下面的单例类++ #pragma once #include "stdafx.h" #include <iostream> class God { private: static God* firstObject; God() { if (firstObject != NULL) firstObject = this; } public: static God* BuildGod()

我试着用C编写下面的单例类++

#pragma once
#include "stdafx.h"
#include <iostream>

class God
{
private:
    static God* firstObject;
    God()
    {
        if (firstObject != NULL)
            firstObject = this;
    }
public:
    static God* BuildGod()
    {
        if (firstObject != NULL)
            return firstObject;
        else {
            God();
            return firstObject;
        }
    }
};
不幸的是,它甚至无法编译,并返回以下错误:

LNK2001未解析外部符号“private:static class God*God::firstObject”(?firstObject@God@@0PAV1@A)

LNK1120 1未解析的外部


类的静态成员必须在类之外定义,如

class God
{
...
};

God* God::firstObj;

只需注意,在头文件中包含定义并包含它会带来麻烦。

类的静态成员必须在类之外定义,如

class God
{
...
};

God* God::firstObj;
请注意,在头文件中包含该定义并将其包含在mamy times中会带来麻烦。

实际上,您的问题比生成错误更严重,因为您创建了一个临时对象,并保存了指向该对象的指针以供使用

声明

God();
创建一个临时对象,然后在构造函数中将指向该临时对象的指针保存在
firstObject
中,然后返回该指针。使用该指针将导致未定义的行为

< >在C++中创建单体的一种常用方法是这样的:

class God
{
public:
    static God& get_instance() {
    {
        static God instance;  // This is THE instance
        return instance;
    }

private:
    God() {}
};
实际上,您的问题比生成错误更严重,因为您创建了一个临时对象,并保存了指向它的指针以供使用

声明

God();
创建一个临时对象,然后在构造函数中将指向该临时对象的指针保存在
firstObject
中,然后返回该指针。使用该指针将导致未定义的行为

< >在C++中创建单体的一种常用方法是这样的:

class God
{
public:
    static God& get_instance() {
    {
        static God instance;  // This is THE instance
        return instance;
    }

private:
    God() {}
};

我的天啊,那很好!谢谢编辑:刚刚尝试添加cast操作符以防万一,如图所示:
操作符const char*({return“sup”;}
它再次给我同样的错误现在我看不到你的代码是什么样子,这很管用天哪,工作得很好!谢谢编辑:只是尝试添加cast操作符以防万一,如图所示:
operator const char*({return“sup”;}
它又给了我同样的错误现在我不明白你的代码是什么样子,这很管用,看看你是否有兴趣在C++11中实现线程安全。看看你是否有兴趣在C++11中实现线程安全。