与'operator <<'不匹配(操作数类型为'std :: ostream {aka std :: basic_ostream <char>}')

时间:2018-08-12 17:04:39

标签: c++ operator-overloading ostream

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

错误:no match for 'operator<<' (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+"
}

不确定我的代码有什么问题,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

operator +返回按值,这意味着它返回的是临时值,它不能绑定到非常量(即Complex&)的左值引用,即参数类型的operator<<

您可以将参数类型更改为const Complex&

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 ;
}

答案 1 :(得分:0)

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

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

ostream& operator<<(ostream& out , const Complex& c)