1. 程式人生 > >C++編寫複數類

C++編寫複數類

#include<iostream>

using namespace std;

class complex{

public:

complex(int aa = 0,int bb = 0 ){//建構函式實現在編寫程式碼的同時對其進行初始化

a = aa;

b = bb;

}

complex(complex &p){//複製建構函式的編寫

a = p.a;

b = p.b;

}

friend complex addcomplex(complex a1,complex a2);

void display(){

cout<<a<<"+"<<b<<"i"<<endl;

}

private://私有資料成員,定義負數的實數部分和虛數部分

int a,b;

};

complex addcomplex(complex a1,complex a2){//實現兩複數相加

complex aa3;

aa3.a = a1.a + a2.a;

aa3.b  = a1.b + a2.b ;

return aa3;

};

int main(){

complex pp(5,9);

cout<<"c1 is"<<endl;

pp.display ();

cout<<endl;

complex a1(3,5),a2(9,9);//設計兩個複數型別

complex aa3;

aa3 = addcomplex(a1,a2);

cout<<"c3 is :"<<endl;

aa3.display ();

return 0;

}