C++ - 试图使操作员"<<"过载

C++ - trying to overload "<<" operator

本文关键字:lt 过载 操作员 C++      更新时间:2023-10-16

我正在尝试重载"<<"运算符以调用 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);
}