0
#include <iostream>
using namespace std;

class boiler
{
private:
    static boiler uniqueInstance;

    bool boilerEmpty;
    bool mixtureBoiled;

    boiler()
    {
        boilerEmpty = true;
        mixtureBoiled = false;
    }

public:
    static boiler getInstance()
    {
        if(uniqueInstance == NULL)
        {
            uniqueInstance = new boiler();
        }

        return uniqueInstance;
    }
};

上述代码返回标题中所述的错误。

anisha@linux-y3pi:~> g++ -Wall test.cpp
test.cpp: In static member function ‘static boiler boiler::getInstance()’:
test.cpp:22:26: error: no match for ‘operator==’ in ‘boiler::uniqueInstance == 0l’
test.cpp:24:34: error: no match for ‘operator=’ in ‘boiler::uniqueInstance = (operator new(2u), (<statement>, ((boiler*)<anonymous>)))’
test.cpp:5:1: note: candidate is: boiler& boiler::operator=(const boiler&)

为什么?我们不能将“对象”与 NULL 进行比较吗?有一些语法问题吗?

4

2 回答 2

2

你可能需要一个指针:

static boiler* uniqueInstance;

从那时起,您将在new此处对其进行初始化:

uniqueInstance = new boiler ();

编译器告诉您它无法将 int 的实例boiler与 int (实际上是 long )进行比较。这种比较是不存在的。指针可以与整数类型进行比较,这允许与 0 进行比较。

这里的比较NULL用作检查指针是否已经初始化的一种方法。如何对实例执行此操作并不明显,没有无效或未初始化实例的概念。您可以NULL通过定义适当的 来比较一个对象operator==,但这种比较可能没有意义,因为NULL它通常只是 的另一个名称0

于 2012-05-04T06:06:32.590 回答
1

您声明uniqueInstsance为类实例:

 static boiler uniqueInstance;

但有时将其视为指针:

uniqueInstance = new boiler ();

我认为您应该将其声明为指针,以便您可以动态分配实例:

static boiler* uniqueInstance;

您还需要更改getInstance()以返回指针:

static boiler* getInstance() //...

最后确保你实际上uniqueInstance在类声明之外有一个定义。在 .cpp 文件中的一个位置(不是标题):

boiler* boiler::uniqueInstance;
于 2012-05-04T06:07:39.820 回答