C++ - 试图使操作员"<<"过载
C++ - trying to overload "<<" operator
我正在尝试重载"<<"运算符以调用 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);
}
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- ostream过载时的缓冲区冲洗
- gcc和c++17的过载解析失败
- C++Cast运算符过载
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- <<操作员在下面的行中工作
- 过载'operator new'如何导致无限循环?
- "Inverse SFINAE"避免模棱两可的过载
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- 基于返回类型的转换和过载扣除
- 没有可行的过载'='错误,可能导致这种情况的原因是什么?
- 是否存在包含负号的isdigit函数(过载)
- 过载输出<<用于类的运算符,以打印其中的元组
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- Qt过载数据流运算符<<
- c++11的特定过载<<操作人员
- 过载<<比如cout错误