c++ - C++ 中的空对象

标签 c++ oop

我正在尝试检查 ship 对象是否为 null,但我收到一条错误消息

Crane.cpp:18: error: could not convert ‘((Crane*)this)->Crane::ship.Ship::operator=(((const Ship&)(& Ship(0, std::basic_string, std::allocator >(((const char*)"arrive"), ((const std::allocator&)((const std::allocator)(& std::allocator())))), std::basic_string, std::allocator >(((const char)"Ship"), ((const std::allocator&)((const std::allocator*)(& std::allocator()))))))))’ to ‘bool’

Crane::Crane(int craneId, int craneStatus, bool free, Ship ship)
{
    setCraneId(craneId);
    setCraneStatus(craneStatus);
    setFree(free);
    setShip(ship);
}
Crane::Crane(){}
Crane::~Crane(){}

void Crane::print()
{
    cout << "Crane Id: " << craneId << endl;
    cout << "Crane Status: " << craneStatus << endl;
    cout << "Crane is free: " << free << endl;
    if (ship = NULL) //this is the problem
    {
        cout << " " << endl;
    }
    else
    {
        ship.print();//i have another print method in the Ship class
    }
}

我试过了

if (ship == NULL) 

但是我收到这个错误信息

Crane.cpp:18: error: no match for ‘operator==’ in ‘((Crane*)this)->Crane::ship == 0’

如何正确地做到这一点?

最佳答案

那是因为 ship 不是指向 Ship 的指针,即 Ship* 但它是 Ship对象本身;那么你不能将它转换为 0 这是...指针的空地址。

如果你想要一个指向 Ship 的指针,你应该这样做

Ship* ship = new Ship;
// Catch a std::bad_alloc exception if new fails

然后如果您获得指针作为函数参数,您可以测试它是否为 null:

void foo(Ship* ship_pointer)
{
    if(ship_pointer == 0)
        // Oops pointer is null...
    else
        // Guess it's OK and use it.
}

关于c++ - C++ 中的空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656204/

相关文章:

python - 对象列表 : Efficiently getting a list of sum of ith attribute

c++ - SafeArrayAccessData 会返回一个不同于 pvData 的指针吗?

c++ - 调用后如何保留数组的原始值?

c++ - 在包含正整数和负整数的 vector 中找到最小的缺失整数?

c# - 从基类构造函数中调用虚方法

java - 这是做我正在尝试的事情的正确方法吗?抽象静态变量?

c++ - 如何获取通过与 libcurl 的连接传输的总字节数?

c++ - 在编译时通过 constexpr 或模板函数获取多维 std::array 的大小

python - 面向对象编程不带参数访问类中的函数(python)

c++ - 如何在QT Creator上将QWidget声明为继承类的对象?