[英]Operator Overloading as member function
为什么它给出错误。
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());
}
};
当试图重载赋值运算符时。 Eroor 说:参数太多
我们可以重载哪些运算符作为成员 function 以及什么不能
当将重载运算符定义为成员 function时, this
指针指向的 object 隐含地是第一个参数。 因此,您的运算符重载需要如下所示:
class Complex {
// ...
Complex operator+(const Complex &d) const {
return Complex (real + d.real, imaginary + d.imaginary);
}
};
请注意,您不需要 getter 函数,因为您已经可以访问 class 中的数据成员。
在 class之外,即作为非成员 function,您的重载运算符非常好。
当覆盖具有左右参数的运算符时,您应该只传递正确的参数并像这样声明它:
Complex operator+(const Complex &d){
return Complex(d.getreal() + getreal(), getimaginary() + d.getimaginary());
}
这样做时,当您调用 getreal() 或直接访问该变量而不指定参数时,它将使用运算符的左侧参数。
一些不能重载的运算符有 scope (::)、三元 (:)、sizeof、成员访问 (.) 等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.