【问题标题】:no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}''operator<<' 不匹配(操作数类型是 'std::ostream {aka std::basic_ostream<char>}'
【发布时间】:2018-08-12 17:04:39
【问题描述】:

现在学习 C++,遇到了一些问题。在尝试完成示例并确保其正常运行时遇到错误:

错误:no match for 'operator&lt;&lt;' (operand types are 'std::istream' and 'const int') and Complex。这是我的代码。

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0) {real = r; imag = i;}

    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        return res;
    }

    int getR() const { return real; }

    int getC() const { return imag ; }

    ostream& aff(ostream& out)
    {
       out << real << " + i" << imag ;
       return out ;
    }

    void print() { cout << real << " + i" << imag << endl; }
};

Complex operator + (const Complex & a , const Complex &b )
{
    int r = a.getR() + b.getR();
    int c = a.getC() + b.getC();
    Complex x(r , c);
     return x ;
}


ostream& operator<<(ostream& out , Complex& c)
{
   return c.aff(out) ;
}

int main()
{
    Complex c1(10, 5), c2(2, 4);
    cout <<  c1 + c2  << endl ; // An example call to "operator+"
}

不确定我的代码有什么问题,谁能帮忙?

【问题讨论】:

  • ostream&amp; operator&lt;&lt;(ostream&amp; out , const Complex&amp; c)

标签: c++ operator-overloading ostream


【解决方案1】:

operator +按值返回,即返回的是临时的,不能绑定左值引用到non-const(即Complex&amp;),即operator&lt;&lt;的参数类型.

可以将参数类型改为const Complex&amp;

ostream& operator<<(ostream& out , const Complex& c)
//                                 ~~~~~
{
   return c.aff(out) ;
}

并且您必须将aff 设为const 成员函数,才能在const 对象上调用。

ostream& aff(ostream& out) const
//                         ~~~~~
{
   out << real << " + i" << imag ;
   return out ;
}

【讨论】:

  • 使用 const ostream 会引发错误,我在某处读到,因为您没有更改任何内容,所以使用 const ostream& 总是更好,那么为什么会出现错误:我的代码 ostream& 运算符
  • @gopalakrishna 你做了affconst吗?错误信息是什么?
  • 是的,我收到以下错误:[Error] no matching function for call to 'Complex::aff(const ostream&) const' 。错误不是因为我做了 aff const ,而是将 ostream 作为 const 引用后
  • 你正在改变流的状态。
  • @gopalakrishna 为什么要同时删除两者? out 已修改,因此不应为 constc 未修改,因此应为 const
【解决方案2】:

您的函数正在等待左值引用,并且您尝试打印 c1 + c2 这是一个临时的。

您可以将临时值绑定到 const 左值引用,因此您必须等待 const Complex &amp;c

ostream&amp; operator&lt;&lt;(ostream&amp; out , const Complex&amp; c)

【讨论】:

  • 替换您提到的代码后,这是我得到的错误: [错误] 将 'const Complex' 作为 'std::ostream& Complex::aff(std:: ostream&)' 丢弃限定符 [-fpermissive]
  • 是的,你的函数是“非 const”,就像@songyuanyao 说的那样,让它成为 const,就可以了
  • 创建一个方法 const 告诉你的对象的客户端这个函数不会改变你对象的任何值:)
  • 假设我在这两个地方都删除了 const ,那么它也不起作用。编辑后:ostream& operator
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
相关资源
最近更新 更多