C++ - 试图重载 "<<"运算符

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

我该如何解决?

最佳答案

你做错了。

此模板具有误导性。它的名字很可怕。
这些额外的方法: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);
}

关于C++ - 试图重载 "<<"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50801493/

相关文章:

c++ - _bstr_t 不是已知标识符

c++ - 模板函数 : perform conversion based on typename

php - Woocommerce 电子邮件订单详细信息中的其他列和项目值

c++ - 组合问题 : operator '==' and operator '-'

c++ - 我真的很想解决 'const' map 问题

c++ - C++ 编译器是否将所有后缀运算符重载视为相同(- 和 -- 的后缀版本)?

c++ - 调用父类(super class)构造函数的规则是什么?

c++ - 如何在 OpenCV 中使用 gpu::Stream?

c++ - 指向正确对象但未分配的 Shared_Ptr

c++ - 使用模板参数设置特定成员