最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(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)算符重載的評論 (共 條)

分享到微博請遵守國家法律
虎林市| 运城市| 华坪县| 上思县| 易门县| 桑日县| 富源县| 重庆市| 德保县| 绥宁县| 柘荣县| 赤峰市| 巍山| 织金县| 惠州市| 将乐县| 喀喇沁旗| 元朗区| 广宁县| 依安县| 盐池县| 叶城县| 信宜市| 铁岭县| 丹寨县| 厦门市| 志丹县| 怀远县| 汉中市| 环江| 舟山市| 班玛县| 七台河市| 甘孜县| 正镶白旗| 临桂县| 碌曲县| 富锦市| 清丰县| 西充县| 台北市|