如何检查C++中是否存在对象

pha*_*joe 14 c++ compiler-construction

我正在尝试编写一个函数来检查对象是否存在:

bool UnloadingBay::isEmpty() {
    bool isEmpty = true;
    if(this->unloadingShip != NULL) {
        isEmpty = false;
    }
    return isEmpty;
}
Run Code Online (Sandbox Code Playgroud)

我是C++的新手,并不确定我的Java背景是否令人困惑,但编译器给出了一个错误:

UnloadingBay.cpp:36: error: no match for ‘operator!=’ in ‘((UnloadingBay*)this)->UnloadingBay::unloadingShip != 0’
Run Code Online (Sandbox Code Playgroud)

我似乎无法弄清楚为什么它不起作用.

这是UnloadingBay类的声明:

class UnloadingBay {

    private:
        Ship unloadingShip;

    public:
        UnloadingBay();
        ~UnloadingBay();

        void unloadContainer(Container container);
        void loadContainer(Container container);
        void dockShip(Ship ship);
        void undockShip(Ship ship);
        bool isEmpty();

};
Run Code Online (Sandbox Code Playgroud)

Dou*_* T. 21

听起来你可能需要一个关于C++中"变量"概念的入门读物.

在C++中,每个变量的生命周期都与它的包含范围有关.最简单的例子是函数的局部变量:

void foo() // foo scope begins
{  
    UnloadingShip anUnloadingShip; // constructed with default constructor

    // do stuff without fear!
    anUnloadingShip.Unload();
} // // foo scope ends, anything associated with it guaranteed to go away
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,当输入函数foo(即输入其范围)时,默认构造"anUnloadingShip".不需要"新".当包含范围消失时(在这种情况下当foo退出时),将自动调用用户定义的析构函数来清理UnloadingShip.相关的内存会自动清除.

当包含范围是C++类(也就是说成员变量)时:

class UnloadingBay
{
   int foo;
   UnloadingShip unloadingShip;
};
Run Code Online (Sandbox Code Playgroud)

生命周期与类的实例有关,所以当我们的函数创建一个"UnloadingBay"时

void bar2()
{
    UnloadingBay aBay; /*no new required, default constructor called,
                         which calls UnloadingShip's constructor for
                         it's member unloadingShip*/

    // do stuff!
}  /*destructor fires, which in turn trigger's member's destructors*/
Run Code Online (Sandbox Code Playgroud)

只要"aBay"生活,aBay的成员就会被建造和生存.

这一切都在编译时计算出来.没有运行时引用计数防止破坏.不考虑可能引用指向该变量的任何其他内容.编译器分析我们编写的函数,以确定变量的范围,从而确定变量的生命周期.编译器会看到变量的作用域结束的位置,清理该变量所需的任何内容都将在编译时插入.

C++中的"new","NULL",(不要忘记"删除")与指针一起发挥作用.指针是一种变量,它包含某个对象的内存地址.程序员使用值"NULL"来指示指针不包含地址(即它不指向任何东西).如果您不使用指针,则无需考虑NULL.

在你掌握了C++中变量如何进入和超出范围之前,请避免使用指针.这完全是另一个话题.

祝好运!