与';操作员<<';(操作数类型是';std::ostream{aka std::basic#ostream<;char>;}'; 学习C++现在遇到了一点问题。在尝试完成一个例子并确保它工作的时候,错误进入:

与';操作员<<';(操作数类型是';std::ostream{aka std::basic#ostream<;char>;}'; 学习C++现在遇到了一点问题。在尝试完成一个例子并确保它工作的时候,错误进入:,c++,operator-overloading,ostream,C++,Operator Overloading,Ostream,错误:no match for'operator您的函数正在等待左值引用,您尝试打印的是临时的c1+c2 您可以将临时值绑定到常量左值引用,因此必须等待const Complex&c ostream&operatoroperator+按值返回,这意味着它返回的是临时的,它不能绑定到非常量的左值引用(即Complex&),这是operatorostream&operator的参数类型。替换您提到的代码后,这是我得到的错误:[error]将“const Complex”作为“std::ostream

错误:
no match for'operator您的函数正在等待左值引用,您尝试打印的是临时的
c1+c2

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


ostream&operator
operator+
按值返回,这意味着它返回的是临时的,它不能绑定到非常量的左值引用(即
Complex&
),这是
operator
ostream&operator的参数类型。替换您提到的代码后,这是我得到的错误:[error]将“const Complex”作为“std::ostream&Complex::aff(std::ostream&)”的“this”参数传递会丢弃限定符[-fppermissive]是的,您的函数是“非常量”,如@songyuanyao所说,将其设为常量,这样做完全正确,使方法const告诉对象的客户端此函数不会更改对象的任何值:)假设我在这两个地方都删除了const,那么它也不起作用。编辑后:ostream&operator使用const-ostream会抛出一个错误,我在某个地方读到,由于您没有更改任何内容,所以最好使用const-ostream&,那么为什么会出现错误:我的代码ostream&operator@gopalakrishna您是否进行了
aff
const
?错误消息是什么?是的,我得到了以下错误:[错误]没有匹配的函数来调用'Complex::aff(const ostream&)const'。错误不是因为我设置了aff const,而是在将ostream设置为const引用后,您正在更改流的状态。@gopalakrishna为什么同时删除这两个函数
out
已修改,因此它不应为
const
c
未修改,因此应为
const
#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& operator<<(ostream& out , const Complex& c)
//                                 ~~~~~
{
   return c.aff(out) ;
}
ostream& aff(ostream& out) const
//                         ~~~~~
{
   out << real << " + i" << imag ;
   return out ;
}