操作符重载

复数相加问题的普通做法:

#include<stdio.h>
class Complex
{
	int a;
	int b;
public:
	Complex(int a = 0,int b = 0)
	{
		this-> a = a;
		this-> b = b;
	}
	int getA()
	{
		return a;
	}
	int getB()
	{
		return b;
	}
	friend ComPlex Add(const Complex& p1,const Complex& p2);
};
ComPlex Add(const Complex& p1,const Complex& p2)//友元函数可直接访问私有成员
{
	Complex ret;
	ret.a = p1.a + p2.a;
	ret.b = p1.b + p2.b;
	return ret;
}
int main()
{
	Complex c1 = (1,2);
	Complex c2 = (3,4);
	Complex c3 = Add(c1,c2);
	printf("c3.a = %d,c3.b\n",c3.getA(),c3.getB());
	return 0;
}

操作符重载

通过operator关键字可以定义特殊的函数
operator的本质是通过函数重载操作符
语法:
type operator Sign(const Type p1,const Type p2)
{
	Type ret;
	return ret;
}
//sign为系统预定义的操作符,+ - * /

友元下的操作符重载:

#include<stdio.h>
class Complex
{
	int a;
	int b;
public:
	Complex(int a = 0,int b = 0)
	{
		this-> a = a;
		this-> b = b;
	}
	int getA()
	{
		return a;
	}
	int getB()
	{
		return b;
	}
	friend ComPlex operator + (const Complex& p1,const Complex& p2);
};
ComPlex operator + (const Complex& p1,const Complex& p2)//友元函数可直接访问私有成员
{
	Complex ret;
	ret.a = p1.a + p2.a;
	ret.b = p1.b + p2.b;
	return ret;
}
int main()
{
	Complex c1 = (1,2);
	Complex c2 = (3,4);
	Complex c3 = c1 + c2;//+操作符重载
	printf("c3.a = %d,c3.b\n",c3.getA(),c3.getB());
	return 0;
}

改进:可以将操作符重载函数定义为类的成员函数
比全局操作符重载函数少一个参数(左操作数)
不需要依赖友元就可以完成操作符重载
编译器优先在成员函数中寻找操作符重载函数

class Type
{
public:
	Type operator Sign(const Type& p)
	{
		Type ret;
		return ret;
	}
};
#include<stdio.h>
class Complex
{
	int a;
	int b;
public:
	Complex(int a = 0,int b = 0)
	{
		this-> a = a;
		this-> b = b;
	}
	int getA()
	{
		return a;
	}
	int getB()
	{
		return b;
	}
	ComPlex operator + (const Complex& p)
	{
		Complex ret;
		ret.a = this.a + p.a;
		ret.b = this.b + p.b;
		return ret;
	}
};

int main()
{
	Complex c1 = (1,2);
	Complex c2 = (3,4);
	Complex c3 = c1 + c2;//c1.operator + (c2)
	printf("c3.a = %d,c3.b\n",c3.getA(),c3.getB());
	return 0;
}
上一篇:2021HW期间公布的部分漏洞及利用方式


下一篇:mysql 联合索引使用规则