// P8.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class complex{
float real; //实部
float image; //虚部
public:
//重载运算符"+"的原型
complex operator+(complex right);
//重载运算符"="的定义
complex operator=(complex right);
void set_complex(float re, float im);
void put_complex(char *name);
};
//重载运算符"+"的原型
complex complex::operator+(complex right){
complex temp;
temp.real = this->real + right.real;
temp.image = image + right.real;
return temp;
}
//重载运算符"="的定义
complex complex::operator=(complex right){
real = right.real;
image = right.image;
return *this;
}
//定义set_complex()成员函数
void complex::set_complex(float re, float im)
{
real = re;
image = im;
}
void complex::put_complex(char *name){
cout << name << ": ";
cout << real << ' ';
if (image >= 0.0) cout << '+';
cout << image << "i\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
complex A, B, C; //创建复数对象
A.set_complex(1.2, 0.8);
B.set_complex(0.8, 1.2);
//显示复数数据
A.put_complex("A");
B.put_complex("B");
C = A + B;
C.put_complex("C = A + B");
return 0;
}
//A: 1.2 +0.8i
//B: 0.8 +1.2i
//C = A + B: 2 +1.6i