关闭

运算符重载实例

191人阅读 评论(0) 收藏 举报
//定义复数类的运算符重载
#include <iostream>
using namespace std;
class Complex
{
public:
	Complex() { real=0; imag=0; }
	Complex ( double r, double i )  { real=r; imag=i; }
    Complex operator + (Complex &c1);
    Complex operator - (Complex &c1);
	//Complex operator * (Complex &c1);
	//Complex operator / (Complex &c1);
	void display();
private:
	double real;
	double imag;
};
Complex Complex::operator + (Complex &c1)
{
	Complex c;
	c.real=real+c1.real;
	c.imag=imag+c1.imag;
	return c;
}
Complex Complex::operator - (Complex &c1)
{
	Complex c;
	c.real=real-c1.real;
	c.imag=imag-c1.imag;
	return c;
}
void Complex::display()
{
	cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main()
{
	Complex c(3,4),c1(2,5),c2,c3;
	c2=c+c1;
	c3=c-c1;
	cout<<"c+c1=";
	c2.display();
	cout<<"c-c1=";
	c3.display();
	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13606次
    • 积分:280
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:4篇
    • 译文:0篇
    • 评论:9条
    最新评论