一、实验目的:
①.掌握C++语言多态性的基本概念;
②.掌握运算符重载函数的声明和定义方式;
二、试验任务:
1. 编写一个程序,实现两个负数相加(分别用类外定义运算符重载函数、友元运算符重载函数、成员运算符重载函数);
2.编写一个程序,实现两个负数的乘法;
三、实验代码及运行结果:
①.用类外定义的运算符重载函数实现:
.h文件#include<iostream>
using namespace std;.cpp文件#include "homework.h"class Complex {public:double real;double imag;Complex(double r = 0, double i = 0){real = r;imag = i;}
};Complex operator +(Complex co1, Complex co2)
{Complex temp;temp.real = co1.real + co2.real;temp.imag = co1.imag + co2.imag;return temp;
}int main()
{Complex com1(1.1, 2.2), com2(3.3, 4.4), total1, total2;total1 = operator+(com1, com2);cout << "real1 =" << total1.real << " " << "imag1 =" << total1.imag << endl;total2 = com1 + com2;cout << "real2 =" << total2.real << " " << "imag1 =" << total2.imag << endl;
}

②.用友元运算符重载函数实现:
.h文件#include<iostream>
using namespace std;.cpp文件#include "homework.h"class Complex {double real;double imag;
public:Complex(double r = 0, double i = 0){real = r;imag = i;}void print();friend Complex operator +(Complex ,Complex );
};Complex operator +(Complex co1, Complex co2)
{Complex temp;temp.real = co1.real + co2.real;temp.imag = co1.imag + co2.imag;return temp;
}void Complex::print()
{cout << "total real=" << real << " " << "total imag=" << imag << endl;
}int main()
{Complex com1(1.1, 2.2), com2(3.3, 4.4), total1;total1 = com1 + com2;total1.print();return 0;
}
③.用成员运算符重载函数实现:
.h文件#include<iostream>
using namespace std;.cpp文件#include "homework.h"class Complex {double real;double imag;
public:Complex(double r = 0, double i = 0){real = r;imag = i;}void print();Complex operator +(Complex);
};Complex Complex::operator +(Complex co1)
{Complex temp;temp.real = co1.real + real;temp.imag = co1.imag + imag;return temp;
}void Complex::print()
{cout << "total real=" << real << " " << "total imag=" << imag << endl;
}int main()
{Complex com1(2.3,4.6), com2(3.6,2.8), total1;total1 = com1 + com2;total1.print();return 0;
}
④.采用友元运算符重载函数实现两个复数的相乘:
.h文件#include<iostream>
using namespace std;.cpp文件#include "homework.h"class Complex {double real;double imag;
public:Complex(double r = 0, double i = 0){real = r;imag = i;}void print();friend Complex operator *(Complex ,Complex );
};Complex operator *(Complex co1, Complex co2)
{Complex temp;temp.real = (co1.real*co2.real)-(co1.imag*co2.imag);temp.imag = (co1.real*co2.imag)+(co1.imag*co2.real);return temp;
}void Complex::print()
{cout << "total real=" << real << " " << "total imag=" << imag << endl;
}int main()
{Complex com1(1,2), com2(3,-4), total1;total1 = com1 * com2;total1.print();return 0;
}

三、实验总结
1. 运算符重载的函数格式:
函数类型 operator 运算符名称 (形参表)
{
对运算符的重载处理
}
2.只能对已有的运算符进行重载,不允许用户定义新的运算符;
3. 成员访问运算符. 成员访问指针运算符.* 条件运算符?: 作用域运算符:: 长度运算符size of 不能进行重载;
4.重载不改变优先级和操作对象数目;
5.运算符重载函数的参数至少应有一个是类对象(或类的引用)



















