Zero object in C ++

I am trying to check if the ship object is null, but I got an error

Crane.cpp: 18: error: cannot convert '((Crane *) this) → Crane :: ship.Ship :: operator = (((const Ship &) (& Ship (0, std :: basic_string, std :: allocator> (((const char *) "come"), ((const std :: allocator &) ((const std :: allocator) (& std :: allocator ()))) (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
    }
}

I tried

if (ship == NULL) 

but i get this error message

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

how to do it right?

+3
source share
4

, ship ship, .. a 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 OK and use it.
}
+14

ship - Crane. , NULL. Crane , ship . NULL . , ++, . , , empty ship, a bool if.

+3

?

: ++, Java - , (reference ↔ object). ++ . , - . int double , .. .

+2

if (ship = NULL)

3 :

1) use the comparison operator instead of the assignment operator and overload the Ship == operator to take int - otherwise you can define a global one bool ::operator==(Ship const& ship, int)
2) create a static nullship variable of type Ship so that you can use it for comparison
3) the best thing you can compare with NULL is a pointer, especially in your caseShip*

And it is good practice to take every argument by reference, so it is not copied every time you call a function.

0
source

Source: https://habr.com/ru/post/1763560/


All Articles