加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c中的空对象

发布时间:2020-12-16 10:42:45 所属栏目:百科 来源:网络整理
导读:我试图检查船对象是否为空,但我收到一条错误消息 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)((co
我试图检查船对象是否为空,但我收到一条错误消息

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::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的指针,即Sh??ip *,但它本身就是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.
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读