上机7.1

         C++预定义中的运算符的操作对象只局限于基本的内置数据类型,但是对于我们自定义的类型是没有办法操作的。但是大多时候我们需要对我们定义的类型进行类似的运算,这个时候就需要我们对这么运算符进行重新定义,赋予其新的功能,以满足自身的需求。

类外定义运算符重载函数

#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()
{
	Complex com1(1,2), com2(3, 4), A,B;
	A = com1 * com2;
	cout << "real1=" << A.real<<"" << "imag1=" << A.imag << endl;
	B = operator*(com1, com2);
	cout << "real1=" << B.real << "" << "imag1=" << B.imag << endl;
}

         这个运算符重载函数只能访问类中的公有数据成员,不能访问类的私有数据成员。

友元运算符重载函数

#include<iostream>
using namespace std;
class Complex {
public:
	double real;
	double imag;
	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.imag * co2.real + co1.real * co2.imag;
	return temp;
}
void Complex::print()
{
	cout << "积为real=" << real << " " << "imag=" << imag << endl;
}
int main()
{
	Complex com1(1,2), com2(3, 4), A,B;
	A = com1 * com2;
	A.print();
	return 0;
}

          把运算符重新定义成类的友元函数,称为友元运算符重载函数,可以访问类的私有和保护成员。

成员运算符重载函数

#include<iostream>
using namespace std;
class Complex {
	double real;
	double imag;
public:
	Complex(double r = 0, double i = 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 << "积为real=" << real << " " << "imag=" << imag << endl;
}
int main()
{
	Complex com1(1,2), com2(3, 4), A,B;
	A = com1 * com2;
	A.print();
	return 0;
}

         把运算符重新定义成类的成员函数,称为成员运算符重载函数,可以访问类中的私有和保护成员。

总结

        C++语言中只能对已有的C++运算符进行重载,不允许用户自己定义新的运算符。 C++绝大部分的运算符允许重载,不能重载的运算符只有以下几个:
.  成员访问运算符
.* 成员访问指针运算符
? : 条件运算符
:: 作用域运算符
sizeof 长度运算符 

        重载不能改变运算符的操作对象的个数;重载不能改变运算符原有的优先级;重载不能改变运算符原有的结合特性;运算符重载函数的参数至少有一个是类对象或类对象的引用。

        对双目运算符而言,成员运算符重载函数参数表中含有一个参数,而友元运算符重载函数参数表中含有两个参数; 对单目运算符而言,成员运算符重载函数参数表中没有参数,而友元运算符重载函数参数表中含有一个参数。一般而言,对于双目运算符,将它重载为友元运算符重载函数比重载为成员运算符重载函数便于使用。对于单目运算符,则选择成员运算符函数较好。如果运算符所需的操作数希望有隐式类型转换,则运算符重载必须用友元函数,而不能用成员函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值