所以,我有一个结构 Bike
,看起来像这样
struct Bike {
std::string brand;
std::string model;
bool is_reserved;
friend std::ostream& operator<<(std::ostream out, const Bike& b);
};
std::ostream& operator<<(std::ostream out, const Bike& b) {
return out
<< "| Brand: " << b.brand << '\n'
<< "| Model: " << b.model << '\n';
}
还有一个类BikeRentalService
, 它有一个 std::vector<Bike*>
称为 bikes_m
.这个类还有一个方法print_available_bikes()
,它应该迭代所说的 std::vector<Bike*>
并打印每个 Bike
通过使用重载 operator<<
如上所示。这个方法看起来像这样:
void BikeRentalService::print_available_bikes(std::ostream& out) {
if (bikes_m.empty()) {
out << "| None" << '\n';
}
else {
for (auto bike : bikes_m) {
if (!bike->is_reserved) {
out << bike;
}
}
}
}
问题是使用这个函数只会打印出那些 Bike
的地址对象。使用前取消引用对象 out <<
也不起作用,Visual Studio 表示它无法引用 std::basic_ostream
因为它是一个“已删除的功能”。
将 for 循环写为 (auto *bike : bikes_m)
不会改变任何东西。
最佳答案
重载ostream操作符的正确方法如下:
struct Bike {
std::string brand;
std::string model;
bool is_reserved;
friend std::ostream& operator<<(std::ostream& out, const Bike& b); // <- note passing out by reference
};
std::ostream& operator<<(std::ostream& out, const Bike& b) {
return out
<< "| Brand: " << b.brand << '\n'
<< "| Model: " << b.model << '\n';
}
此外,如@KyleKnoepfel 所述,您应该更改 out << bike;
至 out << *bike;
也是。
关于c++ - 在指向对象的指针上使用 ostream 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37586337/