生活随笔
收集整理的這篇文章主要介紹了
C++基本操作符重载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
操作符重載指的是將C++提供的操作符進行重新定義,使之滿足我們所需要的一些功能。比如類的加減乘除。我們可以定義類中的某一個成員變量進行加減乘除。
在C++中可以重載的操作符有:
+? -? *? /? %? ^? &? |? ~? !? =? <? >? +=? -=? *=? /=? %=? ^=? &=? |=?
<<? >>? <<=? >>=? ==? !=? <=? >=? &&? ||? ++? --? ,? ->*? ->? ()? []?
new? new[]? delete? delete[]
上述操作符中,[]操作符是下標操作符,()操作符是函數調用操作符。自增自減操作符的前置和后置形式都可以重載。長度運算符“sizeof”、條件運算符“:?”成員選擇符“.”、對象選擇符“.*”和域解析操作符“::”不能被重載。
#include <iostream>
using namespace std;class complex
{
public:complex();complex(double a);complex(double a, double b);complex operator+(const complex & A)const;complex operator-(const complex & A)const;complex operator*(const complex & A)const;complex operator/(const complex & A)const;void display()const;
private:double real; //復數的實部double imag; //復數的虛部
};complex::complex()
{real = 0.0;imag = 0.0;
}complex::complex(double a)
{real = a;imag = 0.0;
}complex::complex(double a, double b)
{real = a;imag = b;
}//打印復數
void complex::display()const
{cout<<real<<" + "<<imag<<" i ";
}//重載加法操作符
complex complex::operator+(const complex & A)const
{complex B;B.real = real + A.real;B.imag = imag + A.imag;return B;
}//重載減法操作符
complex complex::operator-(const complex & A)const
{complex B;B.real = real - A.real;B.imag = imag - A.imag;return B;
}//重載乘法操作符
complex complex::operator*(const complex & A)const
{complex B;B.real = real * A.real - imag * A.imag;B.imag = imag * A.real + real * A.imag;return B;
}//重載除法操作符
complex complex::operator/(const complex & A)const
{complex B;double square = A.real * A.real + A.imag * A.imag;B.real = (real * A.real + imag * A.imag)/square;B.imag = (imag * A.real - real * A.imag)/square;return B;
}int main()
{complex c1(4.3, -5.8);complex c2(8.4, 6.7);complex c3;//復數的加法c3 = c1 + c2;cout<<"c1 + c2 = ";c3.display();cout<<endl;//復數的減法c3 = c1 - c2;cout<<"c1 - c2 = ";c3.display();cout<<endl;//復數的乘法c3 = c1 * c2;cout<<"c1 * c2 = ";c3.display();cout<<endl;//復數的除法c3 = c1 / c2;cout<<"c1 / c2 = ";c3.display();cout<<endl;return 0;
}
?
總結
以上是生活随笔為你收集整理的C++基本操作符重载的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。