[英]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.