C++ 语法实验室之operator关键字

C++ operator关键字个人感觉是一个很容易弄晕自己的关键字,尤其他功能之灵活,还有重载隐式转换的功能,我刚学的时候也是茫然的很,所以我在这里

用一个极简Demo来诠释一下这个关键字到底怎么玩。


用好这个关键字(不谈深研只求会用)一定带着这种思想:

      1.所有的运算符都是函数。

      2.重载运算符就是重载函数。

      3.他只是一种函数简写,唯一不同而且有优先级概念,

而且不能想命名什么就是什么。

有了这些潜意识就可以直接上Demo来自己实验实验了,以下就是一个坐标类的operator用法测试

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <math.h>

class Coordinate
{
public:
	Coordinate()
	{
		x=y=0;
	}

	Coordinate(int vecx,int vecy):x(vecx),y(vecy)
	{

	}

	~Coordinate(){}

	int x;
	int y;

	bool operator==( Coordinate &other )
	{
		return this->x==other.x&&this->y==other.y;
	}

	Coordinate& operator=(const int &v)  
	{  
		this->x=v;
		this->y=v;
		return *this;  
	}  
	//前置运算++
	Coordinate& operator++()
	{
		x++; //先增量
		y++;
		return *this;//返回当前对象
	}

	//后置运算++
	Coordinate& operator++(int)
	{
		Coordinate tmp(*this);//创建临时对象
		x++;//先增量
		y++;
		return tmp;//返回临时对象
	}

	//以加法为例子实现+和+=,减乘除都一样
	Coordinate& operator+( Coordinate &other )
	{
		Coordinate result;
		result.x=this->x+other.x;
		return result;
	}

	Coordinate& operator+=( Coordinate &other )
	{
		this->x+=other.y;
		return *this;
	}

	//当把Coordinate和其他类型比较时候可以使用友元重载方式
	friend  bool operator<(const Coordinate & t1,const int &a ){
		int res=sqrt((float)(t1.x*t1.x+t1.y*t1.y));
		return (a < res);
	}

	//常见的就是利用std::cout方式输出
	friend  std::ostream & operator << (std::ostream & os, Coordinate &t1){
		os<<"(X:"<<t1.x<<",Y:"<<t1.y<<")"<<std::endl;
		return os;
	}

	//重载隐式转换
	operator int()
	{
		int res=sqrt((float)(x*x+y*y));
		return res;
	}
private:

};

int main(int argc, char* argv[])
{

	Coordinate a;
	Coordinate b(1,1);

	a=7;//调用operator=等效于a.operator=(7)

	a==b;//成立等效于a.operator==(b);
	a+=b;//成立等效于a.operator+=(b);
	a=a+70;//a+70有隐式转换,所以会等效于a.operator int()+70
	//a+=70;//这行是编译不过的理由很简单,等效于a.operator+=(70)是不行的,他并没有发生隐式转换
	a++;//调用后置运算
	++a;//调用前置运算


	a<8;//成立因为有friend  bool operator<(const Coordinate & t1,const int &a )函数实现
	8>a;//成立但是原因是发生了隐式转换
	//由此可以判断运算符重载的优先级是会大于运算符重载转换的
	//而且如果运算符重载成功则不会导致多处不必要的隐式转换


	std::cout<<a;//调用friend  std::ostream & operator << (std::ostream & os, Coordinate &t1)

	return 0;
}


注意MSDN的规定:https://msdn.microsoft.com/zh-cn/library/vstudio/5tk49fh2(v=vs.110).aspx


实验结果总结:

1.operator能用成员函数方式重载同类之间的运算。

2.operator可以利用友元成员函数方式重载本类和其他类型的运算符

3.operator可以实现重载本类的隐式转换

4.最关键一点一定要把运算符理解为函数,这样所有线索都通了





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值