C ++运算符I / O重载

时间:2015-02-25 19:08:18

标签: c++ operator-overloading

我在为<<类重载Complex运算符时遇到了一个奇怪的问题(复杂类和重载函数不完整,但意思应该相同 - 但如果你觉得那里缺少一些重要的部分,只是提示我;-)):

class Complex {
    float m_fReal;
    float m_fImaginary;
public:
    Complex();
    Complex(float real, float imaginary);
    Complex add(Complex) const;

    friend std::ostream& operator<< 
          (std::ostream& out, Complex cComplex);
};

重载功能:

std::ostream& operator<<(std::ostream& out, Complex cComplex) {
    out << cComplex.m_fReal << " " << cComplex.m_fImaginary;
    return out;
}

添加功能:

Complex Complex::add(Complex cComplex) const {
    return Complex (m_fReal + cComplex.m_fReal,
                    m_fImaginary + cComplex.m_fImaginary);
}

main中的函数调用:

Complex x(1,1), y(2,2);
cout << "x+y=" << x.add(y) << endl;

虽然上述方法有效,但这并不是(只有不同​​的部分)。

Complex课程中的声明:

friend std::ostream& operator<< 
      (std::ostream& out, Complex& cComplex);

定义:

std::ostream& operator<<(std::ostream& out, Complex& cComplex) {
    out << cComplex.m_fReal << " " << cComplex.m_fImaginary;
    return out;
}

我的目的是通过引用传递Complex类。任何人都可以向我解释一下,这段代码出了什么问题,为什么?

2 个答案:

答案 0 :(得分:4)

您需要接受const引用输出的对象。您已将其作为非const引用接受,add的返回无法绑定。

std::ostream& operator<<(std::ostream& out, const Complex& cComplex) {

此设计/行为是为了防止函数期望改变引用参数值的错误,但引用已绑定到未命名的临时对象,换句话说,无法再次访问的内存,使变化毫无意义。

答案 1 :(得分:1)

您的定义应该是

std::ostream& operator<<(std::ostream& out, const Complex& cComplex) {
  out << cComplex.m_fReal << " " << cComplex.m_fImaginary;
  return out;
}

cComplex需要具有const资格才能使用&#34;来访问其私有变量。&#34;