国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

運(yùn)算符重載

2023-02-08 08:23 作者:江不默  | 我要投稿

1.定義:


例:建一個復(fù)數(shù)類,重載+, -

https://blog.csdn.net/qq_40242197/article/details/118584131

法一:將運(yùn)算符重載作為類函數(shù)



#include<iostream>

#include<cmath>

using namespace std;

class complex {

public:

complex(double r = 0.0,double i=0.0) {

real = r;

imag = i;

}

complex operator +(const complex &c2);

complex operator -(const complex &c2);

void show(){

cout<<"real:"<<real<<" "<<"imag:"<<imag<<endl;

}

double getr() const{//const成員只能調(diào)用const函數(shù)

return real;

}

double geti() const{

return imag;

}

private:

double real;

double imag;

};


complex complex::operator+(const complex &b){

complex d(real+b.getr(),imag+b.geti());

return d;

}

complex complex::operator-(const complex &b){

complex d(real-b.getr(),imag-b.geti());//注意順序不能顛倒?

return d;

}?


int main(){

complex a(1,2),b(3,6),c;

c = a+b;

c.show();

c = a-b;

c.show();

return 0;

}


2.規(guī)則

法二:將運(yùn)算符重載為友元函數(shù)

#include<iostream>

#include<cmath>

using namespace std;

class complex {

public:

complex(double r = 0.0,double i=0.0) {

real = r;

imag = i;

}

void show() {

cout<<"real:"<<real<<" "<<"imag:"<<imag<<endl;

}

private:

double real;

double imag;

friend complex operator +(const complex &c1,const complex &c2);

friend complex operator -(const complex &c1,const complex &c2);

};


complex operator+(const complex &a,const complex &b) {

complex d(a.real+b.real,a.imag+b.imag);

return d;

}

complex operator-(const complex &a,const complex &b) {

complex d(a.real-b.real,a.imag-b.imag);

return d;

}


int main() {

complex a(1,2),b(3,6),c;

c = a+b;

c.show();

c = a-b;

c.show();

return 0;

}



運(yùn)算符重載的評論 (共 條)

分享到微博請遵守國家法律
乌兰察布市| 郓城县| 乐都县| 文山县| 庆安县| 衡阳县| 广宁县| 台前县| 开封县| 安徽省| 海林市| 临汾市| 垦利县| 涡阳县| 乌拉特前旗| 固安县| 麟游县| 鄂托克旗| 交城县| 麦盖提县| 资阳市| 含山县| 巴马| 宜章县| 泰来县| 昌黎县| 普定县| 义乌市| 甘肃省| 庐江县| 兴山县| 司法| 阜康市| 宝丰县| 海丰县| 修武县| 青岛市| 海口市| 防城港市| 江门市| 上虞市|