Pergunta

I have an array of pointers to objects

Room *rooms[MAX_ROOMS];

rooms[0] = new Room(101, 1, RT_CLASSIC, 200.00);
rooms[1] = new Room(102, 2, RT_CLASSIC, 280.00);
rooms[2] = new Room(103, 4, RT_FAMILY_SUITE, 360.00);

Class Room has an overloaded friend operator <<:

std::ostream& operator<<(std::ostream &out, const Room &room) {
    return out << room.toString();
}

How do I output rooms array like this:

for(int i = 0; i < num_of_rooms; i++) {
    cout << rooms[i] << "\n";
}

Because now it outputs addresses to Room objects. I need it to call my Room << operator.

Thank you for your answers.

Foi útil?

Solução

Like so:

cout << *(rooms[i]) << "\n";

rooms[i] returns a pointer to a Room, that's why cout is printing the address. To get the object itself, you have to dereference it (like above).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top