C++一天一个程序(四)
#include
using namespace std;
struct complex{
double real, imag;
complex(double = 0.0, double = 0.0);
}
complex:complex(double r, double i)
{
real = r; imag = i;
}
inline ostream& operator<<(ostream &os, const complex &c)
{
os << ‘(’ << c.real << ‘,’ << c.imag << ‘)’;
return os;
}
inline complex operator+(const complex &c1, const
complex &c2)
{ return complex(c1.real+c2.real,c1.imag+c2.imag);
}
復(fù)數(shù)加法運(yùn)算
關(guān)鍵字operator是函數(shù)名的一部分。為實(shí)現(xiàn)兩個(gè)復(fù)數(shù)的加法可以將operator+定義為全局類型。(重載加法運(yùn)算)
關(guān)鍵字內(nèi)聯(lián)(inline)是提示編譯器要把相應(yīng)的代碼“內(nèi)聯(lián)”。
complex operator+(const complex &c1,const complex &c2)
{
complex r;
r.real=c1.real+c2.real;
r.imag=c1.imag+c2.imag;
return r;
}
總結(jié)
以上是生活随笔為你收集整理的C++一天一个程序(四)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 苹果界面的小圈圈怎么设置(苹果界面上的小
- 下一篇: C++一天一个程序(五)