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);
}
復數加法運算
關鍵字operator是函數名的一部分。為實現兩個復數的加法可以將operator+定義為全局類型。(重載加法運算)
關鍵字內聯(inline)是提示編譯器要把相應的代碼“內聯”。
complex operator+(const complex &c1,const complex &c2)
{
complex r;
r.real=c1.real+c2.real;
r.imag=c1.imag+c2.imag;
return r;
}
總結
以上是生活随笔為你收集整理的C++一天一个程序(四)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果界面的小圈圈怎么设置(苹果界面上的小
- 下一篇: C++一天一个程序(五)