c++ - 在指向对象的指针上使用 ostream 重载

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

所以,我有一个结构 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/

相关文章:

c++ - 如果程序在没有sudo的情况下运行,则gtk_init会导致在Ubuntu 16.04上崩溃

c++ - 代码在调试器中有效,但在可执行程序中无效

c++ - if(!(is >> s)) 是什么意思?

c++ - 指针的元素保存为乱码

c++ - 线程和 GUI 处理

c++ - 基于对象中属性的最小对象堆

c++ - 我是否必须手动实现比较运算符的交换性?

c++ - 在基于范围的 for 循环中查找具有连续内存的序列中元素的位置

c++ - 如何使用模板将变量传递给具有任何签名的函数?

c++ - 使用类的非模板版本作为父类