【问题标题】:Using ostream overloading on pointers to objects在指向对象的指针上使用 ostream 重载
【发布时间】: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&lt;Bike*&gt;,称为bikes_m。这个类还有一个方法print_available_bikes(),它应该迭代上述std::vector&lt;Bike*&gt;并使用上面显示的重载operator&lt;&lt;打印每个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 &lt;&lt; 之前取消引用对象也不起作用,Visual Studio 说它不能引用 std::basic_ostream 因为它是一个“已删除函数”。 将 for 循环编写为 (auto *bike : bikes_m) 不会改变任何内容。

【问题讨论】:

  • 根据您的描述,我不清楚您是否尝试过out &lt;&lt; *bike;
  • 您的operator&lt;&lt; 需要参考out。然后使用out &lt;&lt; *bike;。 (虽然我一开始并没有看到使用std::vector&lt;Bike*&gt; 的意义。)
  • 我还应该使用什么?

标签: c++ operator-overloading c++14 auto ostream


【解决方案1】:

重载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 &lt;&lt; bike; 更改为out &lt;&lt; *bike;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2014-07-29
    • 2023-02-09
    • 1970-01-01
    • 2013-08-23
    • 2019-10-11
    相关资源
    最近更新 更多