复数类使用运算符重载函数:+和++运算符

complex.h

#include <iostream.h>
//using namespace std;
class complex {
private:
float real;
float imag;
public:
complex(float r = 0, float i = 0);
void print();
friend complex operator + (const complex &a, const complex &b);
friend complex operator ++(complex &a);
}; 

complex.cpp

#include "complex.h"
complex::complex(float r, float i) {
real = r;
imag = i;
}
void complex::print() {
cout << real;
if (imag != 0)
{
if (imag>0)
cout << "+" << imag << "i";
else
cout << "-" << imag << "i";
}
cout << endl;
}


complex  operator +(const complex &a, const complex &b) {
complex exam;
exam.real = a.real + b.real;
exam.imag = a.imag + b.imag;
return exam;
//return *this;
}
 complex  operator ++(complex &a)
{
// a.real=a.real+1;
// a.imag=a.imag+1;
++a.real;
++a.imag;
return a;
}

main.cpp

#include "1.h"

int main()
{
complex c1(1.5, 2.5), c2(2, 3), c3;
cout << "原始的c1是:";
c1.print();
cout << "原始的c2是:";
c2.print();
c3 = operator+(c1, c2);
// c3=c2+c1;
cout << "c3=c2+c1 is: ";
c3.print();
operator ++(c2);
cout << "after added 1 ,c2 is:";
c2.print();
return 0;

}

转载自书本《面向对象程序设计几C++》

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值