c ++中的空对象

cha*_*wib 3 c++ oop

我试图检查船对象是否为空,但我收到一条错误消息

Crane.cpp:18:错误:无法转换'((Crane*)this) - > Crane :: ship.Ship :: operator =(((const Ship&)(&Ship(0,std :: basic_string,std: :allocator>(((const char*)"到达"),((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 "布尔"

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过了

if (ship == NULL) 
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息

Crane.cpp:18:错误:'(= Crane*)中的'operator =='不匹配 - > Crane :: ship == 0'

怎么做对吗?

Ced*_* H. 14

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

如果你想要一个Ship你应该做的指针

Ship* ship = new Ship;
// Catch a std::bad_alloc exception if new fails
Run Code Online (Sandbox Code Playgroud)

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

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