简体   繁体   English

运算符重载作为成员 function

[英]Operator Overloading as member function

Why is it giving the error.为什么它给出错误。

 class Complex{
    int real,imaginary;
    public:
    Complex():real(0),imaginary(0){};
    Complex(int real, int imaginary):real(real),imaginary(imaginary){};
    int getreal()const{return real;}

    int getimaginary()const{return imaginary;};
    Complex &operator=(const Complex& );
    Complex operator*(){
      return Complex(real,-imaginary);
    }
    Complex  operator+(const Complex &a, const Complex &d){

      return  Complex (d.getreal()+a.getreal(),a.getimaginary()+d.getimaginary());
    }


  };

When trying to overload the assingment operator.当试图重载赋值运算符时。 Eroor says: too many parameter Eroor 说:参数太多

What operators can we overload as member function and what not我们可以重载哪些运算符作为成员 function 以及什么不能

When defining an overloaded operator as a member function , the object pointed at by the this pointer is implicitly the first argument.当将重载运算符定义为成员 function时, this指针指向的 object 隐含地是第一个参数。 So your operator overload needs to look like:因此,您的运算符重载需要如下所示:

class Complex {
  // ...
  Complex  operator+(const Complex &d) const {
    return  Complex (real + d.real, imaginary + d.imaginary);
  }
};

Note that you don't need the getter functions, since you already have access to the data members inside the class.请注意,您不需要 getter 函数,因为您已经可以访问 class 中的数据成员。

Outside the class, ie as a non-member function, your overloaded operator is perfectly fine.在 class之外,即作为非成员 function,您的重载运算符非常好。

When overriding operators that have left and right parameters, you should just pass the right parameter and declare it like this:当覆盖具有左右参数的运算符时,您应该只传递正确的参数并像这样声明它:

Complex operator+(const Complex &d){
    return Complex(d.getreal() + getreal(), getimaginary() + d.getimaginary());
}

When doing that, when you call getreal() or directly access that variable without specifing the parameter, it will use the left parameter of the operator.这样做时,当您调用 getreal() 或直接访问该变量而不指定参数时,它将使用运算符的左侧参数。

Some of the operators that cannot be overloaded are scope (::), ternary (:), sizeof, member access (.) and some others.一些不能重载的运算符有 scope (::)、三元 (:)、sizeof、成员访问 (.) 等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM