我正在尝试编写一个函数来检查对象是否存在:
bool UnloadingBay::isEmpty() {
bool isEmpty = true;
if(this->unloadingShip != NULL) {
isEmpty = false;
}
return isEmpty;
}
我对 C++ 还很陌生,不确定我的 Java 背景是否令人困惑,但编译器给出了错误:
UnloadingBay.cpp:36: error: no match for ‘operator!=’ in ‘((UnloadingBay*)this)->UnloadingBay::unloadingShip != 0’
我似乎不明白为什么它不起作用。
这是 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();
};
听起来您可能需要了解 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
在上面的代码中,“anUnloadingShip”是在进入函数 foo 时默认构造的(即进入其作用域)。不需要“新”。当包含范围消失时(在本例中是 foo 退出时),您的用户定义的析构函数会自动调用来清理 UnloadingShip。关联的内存会自动清理。
当包含范围是 C++ 类(即成员变量)时:
class UnloadingBay
{
int foo;
UnloadingShip unloadingShip;
};
生命周期与类的实例相关,因此当我们的函数创建“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*/
aBay 的成员随着“aBay”的存在而被构建和存在。
这一切都是在编译时解决的。没有运行时引用计数来防止破坏。不考虑任何可能“引用”或“指向”该变量的其他内容。编译器分析我们编写的函数来确定变量的范围,从而确定变量的生命周期。编译器会看到变量的作用域结束的位置,以及清理该变量所需的任何内容都将在编译时插入。 C++ 中的“new”、“NULL”(不要忘记“delete”)与指针一起发挥作用。指针是一种变量,保存某个对象的内存地址。程序员使用值“NULL”来指示指针不保存地址(即它不指向任何东西)。如果您不使用指针,则无需考虑 NULL。 在掌握 C++ 中的变量如何进入和离开作用域之前,请避免使用指针。这完全是另一个话题了。
祝你好运!
我假设 unloadingShip 是一个对象而不是指针,因此该值永远不会为 NULL。
SomeClass 卸载Ship
与
SomeClass *卸载船舶
好吧,你不必编写那么多代码来检查指针是否为 NULL。该方法可以更简单:
另外,它应该被标记为“const”,因为它不会修改对象的状态,并且也可以在常量实例上调用。
在您的情况下,“unloadingShip”是“UnloadingShip”类的一个对象,它不是动态分配的(除非整个类“UnloadingBay”是动态分配的)。因此,检查它是否等于 NULL 没有意义,因为它不是指针。
为了检查对象是否存在,您可以考虑这样做:
someClass *myObj = NULL // Make it null
现在你在哪里传递这个指针,你可以检查:
if(!myObj) // if its set null, it wont pass this condition
myObj = new someClass();
如果你想删除,你可以这样做:
if(myobj)
{
delete myObj;
myObj = NULL;
}
通过这种方式,您可以在删除对象之前或创建新对象之前很好地控制检查对象是否存在。
希望这有帮助!