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

时间:2016-06-02 08:20:01

标签: 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,因为它是一个&#34;已删除的功能&#34;。 将for循环写为(auto *bike : bikes_m)不会改变任何内容。

1 个答案:

答案 0 :(得分: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 << bike;更改为out << *bike;