【问题标题】:Overload left shift operator << to object将左移运算符 << 重载到对象
【发布时间】:2021-04-26 17:06:53
【问题描述】:

我无法重载左移运算符“

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 类型的内容。问题是我做不到。我缺少对象 bar 的对象引用。

我搜索了很多,但只找到了描述要输出到 cout 的运算符的页面。

【问题讨论】:

  • 你有没有把最后一行实现Foo&amp; operator&lt;&lt;() {... return *this;} ?i
  • @MatG 非常感谢!成功了!

标签: c++ operator-overloading


【解决方案1】:

要启用链接,您必须从运算符返回一个引用。当你写

bar << 1 << 2 << 3;

原来是这样

((bar << 1) << 2) << 3;

即在bar &lt;&lt; 1 的结果上调用operator&lt;&lt;,参数为2

问题是我做不到。我缺少对象栏的对象引用。

您似乎错过了您的operator&lt;&lt; 是一个成员函数。在bars 成员函数中*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:虽然 bar &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3; 这样的结构可以在 C++11 之前的几个库中找到,但现在它看起来有点过时了。您宁愿使用列表初始化或提供std::initializer_list&lt;int&gt; 构造函数来启用Foo bar{1,2,3};

【讨论】:

  • 不知道 *this。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多