C++上机实验7:运算符重载

本次实验进行运算符重载实验,实验目的如下:

    掌握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;
}

以上三种方法均可以实现三个复数相乘的运算,以第二个为例,结果如下:

实验心得:运算符重载的概念,就是把运算符当作多态函数,对它们进行重新定义,并赋予新的功能。就是说运算符不仅是一个运算符了,被赋予了新的意义,图中代码便是将*运算符定义成了复数的乘法。其中代码的 :: 为作用域运算符,要注意在进行友元函数定义时,在类外定义友元函数,不需要“类名::”。另外对双目运算符而言,成员运算符重载函数的形参表中仅有一个参数,是运算符的右操作数。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值