【问题标题】:C++ - trying to overload "<<" operatorC++ - 试图重载“<<”运算符
【发布时间】:2018-06-11 15:41:15
【问题描述】:

我试图重载“

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();    
};

我该如何解决?

【问题讨论】:

  • return os;,不是v.init(); 的结果(即void
  • @PiotrSkotnicki 谢谢!这解决了我的问题。
  • 我希望您还需要修改printElements 以使用os

标签: c++ templates operator-overloading ostream


【解决方案1】:

你做错了。

此模板具有误导性。它的名字很可怕。
这些额外的方法:fillVectorprintElementsinit 令人困惑(他们究竟应该做什么?)。
很可能printElements 缺少std::ostream&amp; 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2016-04-08
    • 2012-06-02
    • 2014-01-14
    • 2013-03-23
    • 2013-12-03
    相关资源
    最近更新 更多