How to call << operator on object in array?
-
13-07-2021 - |
문제
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.
해결책
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).
제휴하지 않습니다 StackOverflow