实验目的
掌握c++语言多态性的基本概念
掌握运算符重载函数声明和定义方法
运算符重载的函数格式:
函数类型 operator 运算符名称(形参表)
{
对运算符的重载处理
}
运算符重载规则
(1)除了少数的运算符不能重载(类属关系运算符“,”、作用域分辨符“::”、三目运算符“?:”成员指针运算符“.*”),大部分都可以重载。
(2)重载之后的运算符的优先级和结合性都不会改变。
(3)不能改变原运算符的操作对象个数,同事至少有一个操作对象是自定义类型。
实验内容
编写一个程序,实现两个复数的相乘
1.类外定义运算符重载函数
代码段:
#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.real * co2.imag + co1.imag * co2.real;
return temp;
}
int main()
{
float a, b, c, d;
cout << "请输入两个复数:" << endl;
cin >> a >> b >> c >> d;
Complex com1(a, b), com2(c, d), 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;
}
运算结果:
2.友元运算符重载函数
代码段:
#include<iostream>
using namespace std;
class Complex
{
double real;
double imag;
public:
Complex(double r = 0, double i = 0)
{
real = r; imag = 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.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()
{
float a, b, c, d;
cout << "请输入两个复数:" << endl;
cin >> a >> b >> c >> d;
Complex com1(a, b), com2(c, d), total1;
total1 = com1 * com2;
total1.print();
return 0;
}
运算结果:
在C++中,友元(friend)提供了在类外访问类中任意成员的方法(特权)
friend用于应对编程中一些比较特殊的情况,绝大多数情况下不需要使用,乱使用只会使C++变成C,甚至更糟。
友元函数虽然可以访问类对象的私有成员,但是不是成员函数,因此,在类的外部定义友元函数时,不需要"类名::".
3.成员运算符重载函数
代码段:
#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 - imag * c.imag;
temp.imag = real * c.imag + imag * c.real;
return temp;
}
void Complex::print()
{
cout << "total real=" << real << "" << " total imag=" << imag << endl;
}
int main()
{
float a, b, c, d;
cout << "请输入两个复数:" << endl;
cin >> a >> b >> c >> d;
Complex com1(a, b), com2(c, d), total1;
total1 = com1 * com2;
total1.print();
return 0;
}
运算结果:
对双目运算符而言,成员运算符重载函数的形参表中仅有一个参数,是运算符的右操作数。
另一个操作数(左操作数)是隐含的,是该类的当前对象,他是通过this指针隐含传递给函数。
注意事项:
1.除了类属关系运算符”.“、成员指针运算符”.*“、作用域运算符”::“、sizeof运算符和三目运算符”?:“以外,C++中的所有运算符都可以重载。
2.重载运算符限制在C++语言中已有的运算符范围内的允许重载的运算符之中,不能创建新的运算符。
3.运算符重载实质上是函数重载,因此编译程序对运算符重载的选择,遵循函数重载的选择原则。
4.重载之后的运算符不能改变运算符的优先级和结合性,也不能改变运算符操作数的个数及语法结构。
5.运算符重载不能改变该运算符用于内部类型对象的含义。它只能和用户自定义类型的对象一起使用,或者用于用户自定义类型的对象和内部类型的对象混合使用时。
6.运算符重载是针对新类型数据的实际需要对原有运算符进行的适当的改造,重载的功能应当与原有功能相类似,避免没有目的地使用重载运算符。