gpt4 book ai didi

c++ - 如何在数组中的对象上调用 << 运算符?

转载 作者:行者123 更新时间:2023-11-27 23:21:02 25 4
gpt4 key购买 nike

我有一个指向对象的指针数组

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);

Room 有一个重载的友元运算符 <<:

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

如何像这样输出 rooms 数组:

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

因为现在它将地址输出到 Room 对象。我需要它来调用我的 Room << 接线员。

感谢您的回答。

最佳答案

像这样:

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

rooms[i] 返回指向 Room 的指针,这就是 cout 打印地址的原因。要获取对象本身,您必须取消引用它(如上所示)。

关于c++ - 如何在数组中的对象上调用 << 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13034155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com