日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++基本操作符重载

發(fā)布時(shí)間:2025/4/5 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++基本操作符重载 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

?

操作符重載指的是將C++提供的操作符進(jìn)行重新定義,使之滿足我們所需要的一些功能。比如類的加減乘除。我們可以定義類中的某一個(gè)成員變量進(jìn)行加減乘除。

在C++中可以重載的操作符有:
+? -? *? /? %? ^? &? |? ~? !? =? <? >? +=? -=? *=? /=? %=? ^=? &=? |=?
<<? >>? <<=? >>=? ==? !=? <=? >=? &&? ||? ++? --? ,? ->*? ->? ()? []?
new? new[]? delete? delete[]

上述操作符中,[]操作符是下標(biāo)操作符,()操作符是函數(shù)調(diào)用操作符。自增自減操作符的前置和后置形式都可以重載。長度運(yùn)算符“sizeof”、條件運(yùn)算符“:?”成員選擇符“.”、對(duì)象選擇符“.*”和域解析操作符“::”不能被重載。

#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; //復(fù)數(shù)的實(shí)部double imag; //復(fù)數(shù)的虛部 };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; }//打印復(fù)數(shù) 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;//復(fù)數(shù)的加法c3 = c1 + c2;cout<<"c1 + c2 = ";c3.display();cout<<endl;//復(fù)數(shù)的減法c3 = c1 - c2;cout<<"c1 - c2 = ";c3.display();cout<<endl;//復(fù)數(shù)的乘法c3 = c1 * c2;cout<<"c1 * c2 = ";c3.display();cout<<endl;//復(fù)數(shù)的除法c3 = c1 / c2;cout<<"c1 / c2 = ";c3.display();cout<<endl;return 0; }

?

總結(jié)

以上是生活随笔為你收集整理的C++基本操作符重载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。