实验目的:1.掌握C++语言多态性的基本概念
2.掌握运算符重载函数的声明和定义方法
实验结果如下:
1.类外定义运算符重载函数
2.友元运算符重载函数
3.类内定义运算符重载函数
代码如下:
1.#include
using namespace std;
class Complex{
public:
double real;
double imag;
Complex(double real1=0,double imag1=0)
{
real = real1;
imag = imag1;
}
};
Complex operator*(Complex co1,Complex co2)//类外定义重载函数
{
Complex temp;
temp.real = (co1.realco2.real)-(co1.imagco2.imag);
temp.imag = (co1.imagco2.real+co1.realco2.imag);
return temp;
}
int main()
{
Complex com1(1,2),com2(3,4),total1,total2;
total1 = operator*(com1,com2);
cout<<"total1-real = "<<total1.real<<endl;
cout<<"total1-imag = "<<total1.imag<<endl;
total2 = com1 * com2;
cout<<"total2-real = "<<total2.real<<endl;
cout<<"total2-imag = "<<total2.imag<<endl;
}
2.#include
using namespace std;
class Complex{
double real; //默认定义为private
double imag;
public:
Complex(double real1=0,double imag1=0)
{
real = real1;
imag = imag1;
}
void print();
friend Complex operator*(Complex co1,Complex co2);//定义友元函数
};
void Complex::print()
{
cout<<"total-real = "<<real<<endl;
cout<<"total-imag = "<<imag<<endl;
}
Complex operator*(Complex co1,Complex co2)
{
Complex temp;
temp.real = (co1.realco2.real)-(co1.imagco2.imag);
temp.imag = (co1.imagco2.real+co1.realco2.imag);
return temp;
}
int main()
{
Complex com1(1,2),com2(3,4),total;
total = com1*com2;
total.print();
return 0;
}
3.#include
using namespace std;
class Complex{
double real; //默认定义为private
double imag;
public:
Complex(double real1=0,double imag1=0)
{
real = real1;
imag = imag1;
}
void print();
Complex operator*(Complex c);//类内定义重载函数
};
void Complex::print()
{
cout<<"total-real = "<<real<<endl;
cout<<"total-imag = "<<imag<<endl;
}
Complex Complex::operator*(Complex c)
{
Complex temp;
temp.real = (realc.real)-(imagc.imag);
temp.imag = (imagc.real+realc.imag);
return temp;
}
int main()
{
Complex com1(1,2),com2(3,4),total;
total = com1*com2;
total.print();
return 0;
}
心得:
运算符重载函数充分展示了多态性的特点,使得运算符的运用更加多样性,更加便利。运算符函数重载有多种方式,每种方式都有各自的特点。
类外定义重载函数
友元定义重载函数
类内定义重载函数
可以在不同情况下选择不同的方式重载
本周次实验重新复习了类内 类外 以及友元函数的特点及注意事项,收获颇多。