C ++ - 尝试重载“<<”操作者

时间:2018-06-11 15:41:16

标签: c++ templates operator-overloading ostream

我正在尝试重载“<<”运算符调用2个方法,但编译器给出了一个错误:

invalid initialization of non-const reference of type 'std::ostream&' 
{aka 'std::basic_ostream<char>&' from an rvalue of type 'void'
        return v.init();

这是我的班级定义:

template<class T>
class Vector
{
private:
    std::vector<T> _Vec;
public:
    void fillVector();
    void printElements();
    void init() { fillVector(); printElements(); }
    friend std::ostream& operator<<(std::ostream& os, Vector& v) {
            return v.init();    
};

我该如何解决?

1 个答案:

答案 0 :(得分:1)

你做错了。

此模板具有误导性。它的名字太可怕了 这些额外的方法:fillVectorprintElementsinit令人困惑(他们应该做什么?)。
最有可能printElements缺少std::ostream& stream参数(可能还有返回类型)。

您没有描述您尝试实施的功能类型。最有可能这就是你需要的:

template<class T>
class PrintContainer
{
public:
    PrintContainer(const T& container)
    : mContainer { container }
    {}

    std::ostream& printTo(std::ostream& stream) const {
        // or whatever you need here
        for (const auto& x : mContainer) {
             stream << x << ", ";
        }
        return stream;
    }

private:
    const T& mContainer;
};

template<class T>
std::ostream& operator<<(std::ostream& os, const PrintContainer<T>& p) {
    return p.printTo(os);
}