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;

发布了14 篇原创文章 · 获赞 0 · 访问量 218

猜你喜欢

转载自blog.csdn.net/weixin_41210618/article/details/104715597
今日推荐