【发布时间】:2016-06-02 08:20:01
【问题描述】:
所以,我有一个结构体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*>并使用上面显示的重载operator<<打印每个Bike。这个方法看起来像这样:
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) 不会改变任何内容。
【问题讨论】:
-
根据您的描述,我不清楚您是否尝试过
out << *bike;。 -
您的
operator<<需要参考out。然后使用out << *bike;。 (虽然我一开始并没有看到使用std::vector<Bike*>的意义。) -
我还应该使用什么?
标签: c++ operator-overloading c++14 auto ostream