10.1 分别通过函数和重载运算符来实现复数相加
生活随笔
收集整理的這篇文章主要介紹了
10.1 分别通过函数和重载运算符来实现复数相加
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include <iostream>
using namespace std;
class Complex
{
public:Complex(){real=0;imag=0;}Complex(int r,int i){real=r;imag=i;}Complex complex_add(Complex &c2)//復(fù)數(shù)相加函數(shù){Complex c;c.real=real+c2.real;c.imag=imag+c2.imag;return c;}void display();
private:int real,imag;
};
void Complex::display()
{cout<<'('<<real<<','<<imag<<"i)"<<endl;
}
int main()
{Complex c1(3,4),c2(-5,10),c3;c3=c1.complex_add(c2);cout<<"c1=";c1.display();cout<<"c2=";c2.display();cout<<"c1+c2=";c3.display();return 0;
}
#include <iostream>
using namespace std;
class Complex
{
public:Complex(){real=0;imag=0;}Complex(int r,int i){real=r;imag=i;}Complex operator+(Complex &c2)//重載運(yùn)算符的函數(shù),用于復(fù)數(shù)相加{Complex c;c.real=real+c2.real;c.imag=imag+c2.imag;return c;}void display();
private:int real,imag;
};
void Complex::display()
{cout<<'('<<real<<','<<imag<<"i)"<<endl;
}
int main()
{Complex c1(3,4),c2(-5,10),c3;c3=c1+c2;//系統(tǒng)自動調(diào)用c1.operator+(c2)來完成c1+c2;cout<<"c1=";c1.display();cout<<"c2=";c2.display();cout<<"c1+c2=";c3.display();return 0;
}
重載運(yùn)算符函數(shù)的一般格式如下:
函數(shù)類型 operator運(yùn)算符名稱(參數(shù)列表)
{對運(yùn)算符重載的處理}
總結(jié)
以上是生活随笔為你收集整理的10.1 分别通过函数和重载运算符来实现复数相加的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。