我无法重载左移运算符"<<",所以我可以使用以下代码:
Foo bar;
bar << 1 << 2 << 3;
我的类Foo看起来像这样:
class Foo{
private:
vector<int> list;
public:
Foo();
void operator<<(int input);
};
实现如下:
void Foo::operator<<(int input)
{
// here i want to add the different int values to the vector
// the implementation is not the problem
}
代码不起作用,我收到错误"左操作数类型为'void'"。当我将返回类型更改为Foo 时,它会告诉我返回Foo类型的东西。问题是我不能。我缺少对象栏的对象引用。
我搜索了很多,但只找到了描述操作员输出到 cout 的页面。
若要启用链接,必须从运算符返回引用。当你写的时候
bar << 1 << 2 << 3;
那实际上是
((bar << 1) << 2) << 3;
即operator<<
是在参数2
的bar << 1
结果上调用的。
问题是我不能。我缺少对象栏的对象引用。
您似乎忽略了您的operator<<
是成员函数。在bar
的成员函数中,*this
是对bar
对象的引用:
#include <vector>
#include <iostream>
class Foo{
private:
std::vector<int> list;
public:
Foo() {}
Foo& operator<<(int input);
void print() const { for (const auto& e : list) std::cout << e << ' ';}
};
Foo& Foo::operator<<(int input)
{
list.push_back(input);
return *this;
}
int main() {
Foo bar;
bar << 1 << 2 << 3;
bar.print();
}
PS:虽然在 C++11 之前的几个库中可以找到诸如bar << 1 << 2 << 3;
之类的结构,但现在它看起来有点过时了。您宁愿使用列表初始化或提供std::initializer_list<int>
构造函数来启用Foo bar{1,2,3};
。