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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3640739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:21:16  来源:igfitidea点击:

how can I check if an object exists in C++

c++compiler-construction

提问by pharma_joe

I am trying to write a function that will check if an object exists:

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

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

I am pretty new to C++ and not sure if my Java background is confusing something, but the compiler gives an error:

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

UnloadingBay.cpp:36: error: no match for ‘operator!=' in ‘((UnloadingBay*)this)->UnloadingBay::unloadingShip != 0'

I can't seem to figure out why it doesn't work.

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

Here is the declaration for class UnloadingBay:

这是 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();

};

回答by Doug T.

It sounds like you may need a primer on the concept of a "variable" in C++.

听起来您可能需要了解 C++ 中“变量”的概念。

In C++ every variable's lifetime is tied to it's encompassing scope. The simplest example of this is a function's local variables:

在 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

In the above code "anUnloadingShip" is default constructed when the function foo is entered (ie its scope is entered). No "new" required. When the encompassing scope goes away (in this case when foo exits), your user-defined destructor is automatically called to clean up the UnloadingShip. The associated memory is automatically cleaned up.

在上面的代码中,“anUnloadingShip”是在输入函数 foo 时默认构造的(即输入其作用域)。不需要“新”。当包含的作用域消失时(在这种情况下,当 foo 退出时),您的用户定义的析构函数将被自动调用以清理 UnloadingShip。关联的内存会自动清理。

When the encompassing scope is a C++ class (that is to say a member variable):

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

class UnloadingBay
{
   int foo;
   UnloadingShip unloadingShip;
};

the lifetime is tied to the instances of the class, so when our function creates an "UnloadingBay"

生命周期与类的实例相关,所以当我们的函数创建一个“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*/

the members of aBay are constructed and live as long as "aBay" lives.

aBay 的成员被构建并且与“aBay”的存在时间一样长。

This is all figured out at compile time. There is no run-time reference counting preventing destruction. No considerations are made for anything else that might refer toor point tothat variable. The compiler analyzes the functions we wrote to determine the scope, and therefore lifetime, of the variables. The compiler sees where a variable's scope ends and anything needed to clean up that variable will get inserted at compile time.

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

"new", "NULL", (don't forget "delete") in C++ come into play with pointers. Pointers are a type of variable that holds a memory address of some object. Programmers use the value "NULL" to indicate that a pointer doesn't hold an address (ie it doesn't point to anything). If you aren't using pointers, you don't need to think about NULL.

C++ 中的“new”、“NULL”(不要忘记“delete”)与指针有关。指针是一种变量,用于保存某个对象的内存地址。程序员使用值“NULL”来表示指针不持有地址(即它不指向任何东西)。如果您不使用指针,则无需考虑 NULL。

Until you've mastered how variables in C++ go in and out of scope, avoid pointers. It's another topic entirely.

在您掌握 C++ 中的变量如何进出作用域之前,请避免使用指针。这完全是另一个话题。

Good luck!

祝你好运!

回答by GWW

I'm assuming unloadingShip is an object and not a pointer so the value could never be NULL.

我假设 unloadingShip 是一个对象而不是一个指针,因此该值永远不会为 NULL。

ie.

IE。

SomeClass unloadingShip

SomeClass卸货船

versus

相对

SomeClass *unloadingShip

SomeClass *unloadingShip

回答by GWW

Well, you don't have to write so much code to check if a pointer is NULL or not. The method could be a lot simpler:

好吧,您不必编写太多代码来检查指针是否为 NULL。该方法可以简单得多:

bool UnloadingBay::isEmpty() const {
    return unloadingShip == NULL;
}

Plus, it should be marked as "const" because it does not modify the state of the object and can be called on constant instances as well.

另外,它应该被标记为“const”,因为它不会修改对象的状态并且也可以在常量实例上调用。

In your case, "unloadingShip" is an object of class "UnloadingShip" which is not dynamically allocated (except when the whole class "UnloadingBay" is allocated dynamically). Thus, checking if it equals to NULL doesn't make sense because it is not a pointer.

在您的情况下,“unloadingShip”是“UnloadingShip”类的一个对象,它不是动态分配的(除非整个类“UnloadingBay”都是动态分配的)。因此,检查它是否等于 NULL 没有意义,因为它不是指针。

回答by linuxeasy

For checking, if an object exists, you can consider going this way:

为了检查,如果一个对象存在,你可以考虑这样做:

create a pointer to your object:

创建一个指向您的对象的指针:

someClass *myObj = NULL // Make it null

and now where you pass this pointer, you can check:

现在你传递这个指针的地方,你可以检查:

if(!myObj)  // if its set null, it wont pass this condition
    myObj = new someClass();

and then in case you want to delete, you can do this:

然后如果你想删除,你可以这样做:

if(myobj)
{
    delete myObj;
    myObj = NULL;
}

so in this way, you can have a good control on checking whether your object exists, before deleting it or before creating a new one.

因此,通过这种方式,您可以很好地控制在删除对象之前或创建新对象之前检查对象是否存在。

Hope this helps!

希望这可以帮助!