以下代码实现了模拟复数加法功能
Complex.h定义了复数类
#ifndef COMPLEX_H
#define COMPLEX_H
using namespace std;
class Complex{
private:
double real;
double image;
public:
Complex():real(0),image(0){
}
Complex(double r,double i):real(r),image(i){
}
~Complex(){
}
//运算符重载operator+ 替代 Add()
Complex operator+(const Complex& c) const
{
double dr=real +c.real;
double di=image+c.image;
Complex d(dr,di);
return d;
}
void input(){
cin >>real>>image;
}
void output(){
cout<
main.cpp定义了主程序
#include
#include "Complex.h"
using namespace std;
int main(int argc, char** argv) {
Complex a;
a.input();
Complex b(3,4);
//运算符重载用a+b 替代a.Add(b)
Complex c=a+b;
c.output();
return 0;
}


![[c++类的运用]运算符重载实现复数加法 [c++类的运用]运算符重载实现复数加法](http://www.mshxw.com/aiimages/31/429415.png)
