关于c++中运算符重载
?
通俗的講,運算符重載就是把運算符賦予新的功能,比如說 + 有整數相加 浮點數相加的功能,但是沒有復數相加的功能,這時我們通過運算符重載,使得 + 具有復數相加的功能,這就叫做運算符重載,本質上, 運算符重載是函數的重載。
?
重載運算符使具有特殊名稱的函數, 形式如下:
1 返回類型 operator運算符號(形式參數列表) 2 { 3 函數體 4 }1 operator后接需要重載的運算符, 成為運算符函數。
2 運算符函數的函數名就是“ operator運算符號” ?//operator+ ?是函數名
?
下面通過設計一個復數類實現 + 的重載
?
1 #include <iostream> 2 using namespace std; 3 class complex //復數類 4 { 5 public: 6 complex(double r=0.0,double i=0.0)//構造函數 {real=r; imag=i; } 7 complex operator +(complex &c2); //重載+運算符 8 complex operator -(complex &c2); //重載-運算符 9 void display() 10 { 11 cout<<real<<"+"<<imag<<"i"<<endl; 12 } 13 private: 14 double real; //實部 15 double imag; //虛部 16 }; complex complex::operator +(complex &c2) 18 { complex c; 20 c.real=c2.real+real; 21 c.imag=c2.imag+imag; 22 return c; 23 } 24 complex complex::operator -(complex &c2) 25 { complex c; 27 c.real=real-c2.real; //順序不能顛倒 28 c.imag=imag-c2.imag; 29 return c; 30 } 31 int main() 32 { complex c1(1,2),c2(3,4),c3; 34 c3=c2+c1; c3.display(); //輸出4+6i 36 c3=c2-c1; c3.display(); //輸出2+2i 38 return 0; 39 }只有類的普通成員函數才有this指針 類的有元函數 靜態成員函數都是沒有this指針的
?
?
當運算符重載為友元函數時, 運算符函數的形式參數的個數和運算符規定的運算對象個數一致 一般我們也是采用這種方式
形式如下:
class 類名{ //類體
……
//友元聲明
friend 返回類型 operator 運算符號(形式參數列表);
};
返回類型 operator 運算符號(形式參數列表)
{
函數體
}
還是以 + - 運算符為例
1 #include <iostream> 2 using namespace std; 3 class complex //復數類 4 { 5 public: 6 complex(double r=0.0,double i=0.0) {real=r; imag=i;}//構造函數 7 friend complex operator +(const complex &c1,const complex &c2); //重載+運算符 8 friend complex operator -(const complex &c1,const complex &c2); //重載-運算符 9 void display() 10 { cout<<real<<"+"<<imag<<"i"<<endl; } 11 private: 12 double real; //實部 13 double imag; //虛部 14 }; 15 complex operator +(const complex &c1,const complex &c2) 16 { complex c3; 17 c3.real=c1.real+c2.real; 18 c3.imag=c1.imag+c2.imag; 19 return c3; 20 } 21 complex operator -(const complex &c1,const complex &c2) 22 { complex c3; 23 c3.real=c1.real-c2.real; 24 c3.imag=c1.imag-c2.imag; 25 return c3; 26 } 27 int main() 28 { complex c1(1,2),c2(3,4),c3; 29 c3=c2+c1; c3.display(); //輸出4+6i 30 c3=c2-c1; c3.display(); //輸出2+2i 31 return 0; 32 }?
?
重載運算符的規則
?( 1) C++絕大部分的運算符可以重載, 不能重載的運算符有:. .* :: ?: sizeof
?( 2) 不能改變運算符的優先級、 結合型和運算對象數目。
?( 3) 運算符重載函數不能使用默認參數。
?( 4) 重載運算符必須具有一個類對象( 或類對象的引用) 的參數,不能全部是C++的內置數據類型。
?( 5) 一般若運算結果作為左值則返回類型為引用類型; 若運算結果要作為右值, 則返回對象。
?( 6) 重載運算符的功能應該與原來的功能一致。
?
轉載于:https://www.cnblogs.com/tiantiantian-dianzi/p/5625438.html
總結
以上是生活随笔為你收集整理的关于c++中运算符重载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kindle使用技巧
- 下一篇: url与uri的区别