我试图重载“<<”运算符来调用 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();
};
我该如何解决?
最佳答案
你做错了。
此模板具有误导性。它的名字很可怕。
这些额外的方法:fillVector
、printElements
、init
令人困惑(它们究竟应该做什么?)。
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/