/**
*cppTest-7.1:运算符重载
*
*author 炜sama
*/
#include<iostream.h>
class complex{
float real;
float imag;
public:
complex(float r=0,float i=0){ real=r; imag=i; }
void show(){ cout<<real<<"+"<<imag<<"j"<<endl; }
complex operator+(complex &c);
};
complex complex::operator+(complex &c)
{
float r,i;
r=real+c.real;
i=imag+c.imag;
return complex(r,i);
}
void main()
{
complex x(5,2);
complex y(4,3);
complex z;
z=x+y;
z.show();
//这个程序的输出结果是9+5j,这表明语句z=x+y完成了对复数的加运算。
//这个语句的执行过程可以解释成:z=operator+(x,y);
}
cppTest-7.1:运算符重载
最新推荐文章于 2025-12-15 07:52:40 发布
本文详细介绍了C++中运算符重载的概念、语法和实践案例,通过一个具体的例子展示了如何实现复数加法运算,并解释了语句的执行过程。
1631

被折叠的 条评论
为什么被折叠?



