本次实验进行运算符重载实验,实验目的如下:
掌握C++语言多态性的基本概念;
掌握运算符重载函数的声明和定义方法。
运算符重载的基本格式如下:
函数类型 operator 运算符名称(形参表)
{
对运算符的重载处理
}
实验要求用三种不同方法设计程序使两复数相乘,并体验其中区别。
第一种:类外定义运算符重载函数
#include<iostream>
using namespace std;
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-co1.imag*co2.imag;
temp.imag = co1.imag * co2.real+co1.real*co2.imag;
return temp;
}
int main()
{
float x1,x2,y1,y2;
cout << "分别输入两个复数的实部和虚部" << endl;
cin >> x1 >> y1 >> x2 >> y2;
Complex com1(x1, y1), com2(x2, y2), total1, total2;
total1 = operator*(com1, com2);
cout << "real1=" << total1.real << "imag1=" << total1.imag << endl;
total2 = com1 * com2;
cout << "real2=" << total2.real << "imag2=" << total2.imag << endl;
return 0;
}
第二种:友元运算符重载函数
#include<iostream>
using namespace std;
class Complex {
private:
double real;
double image;
public:
Complex(double r = 0, double i = 0) {
real = r;
image = i;
}
void print();
friend Complex operator*(Complex co1, Complex co2);
};
Complex operator*(Complex co1, Complex co2) {
Complex temp;
temp.real = co1.real * co2.real - co1.image * co2.image;
temp.image = co1.real * co2.image + co1.image * co2.real;
return temp;
}
void Complex::print() {
cout << "total real=" << real << " " << "total image=" << image << endl;
}
int main() {
Complex com1(1.1, 2.2), com2(3.3, 4.4), total1;
total1 = com1 * com2;
total1.print();
return 0;
第三种:成员运算符重载函数
#include<iostream>
using namespace std;
class Complex
{
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0);
void print();
Complex operator+(Complex c);
};
Complex::Complex(double r, double i)
{
real = r; imag = i;
}
Complex Complex :: operator*(Complex c)
{
Complex temp;
temp.real = real * c.real - image * c.image;
temp.image = real * c.image + image * c.real;
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;
}
以上三种方法均可以实现三个复数相乘的运算,以第二个为例,结果如下:
实验心得:运算符重载的概念,就是把运算符当作多态函数,对它们进行重新定义,并赋予新的功能。就是说运算符不仅是一个运算符了,被赋予了新的意义,图中代码便是将*运算符定义成了复数的乘法。其中代码的 :: 为作用域运算符,要注意在进行友元函数定义时,在类外定义友元函数,不需要“类名::”。另外对双目运算符而言,成员运算符重载函数的形参表中仅有一个参数,是运算符的右操作数。