c++运算符重载

当要对一个自定义的对象进行运算时(运用运算符操作对象),就需要运算符重载。
平时int,float,double类型可以直接用+,-,*,/符号进行运算,<<进行输出。但是自己定义的对象(class)却不可以用他们进行运算,但是int 等也是一个对象(class),这就是说明我们自定义的对象也可是使用运算符进行操作,但是底层运算符并没有办法帮我们定义我们的对象运算,这个时候就需要我们重载运算符,来支持我们的自定义兑现进行操作。


*1.运算符。
运算符就是操作符,对运算符前一个变量进行操作,并返回一个数据类型。可以先简单认为+,-,*,/ 和 函数调用运算符 “ . ” 一样。
(Friend 先排除友缘重载)
int c= int a +int b;// c = a.operator+( int b)// a调用+号对b操作,返回个 int。
int a+=int b //a.operator+=( int b) // a调用+=号对b操作,返回个 int。
2.运算符重载
1)当重载友元函数时,将没有隐含的参数this指针。这样,对双目运算符,友元函数有2个参数,对单目运算符,友元函数有一个参数。
(2)有些运行符不能重载为友元函数,它们是:=,(),[]和->。
(3)运算符重载的时候要嘛使用友元,要嘛使用成员,二者选其一,不要在一个类中对一个运算符同时用这两种方法重载,会出现二义性,编译器无法编译。(原因在于友元不属于任何对象,没有作用域,只能在类内定义,没有this指针,而成员函数有this指针。)
1.const test operator+(const test & other);
//const test operator+(this,const test & other);
2.friend const test operator+(test &intValue, const test & other);

test3=test1+test2;//同时定义,test1就都可以调用1和2,编译器就会报错
Tips:一元运算符,复合赋值运算符,建议重载为成员函数。(+= ,-=,&=,等),因为都是对对象自身的操作,并返回自己。其他的建议用友元重载。
先定义一个Stone类,类有数量和重量属性,现在计算现有石头的总重。

class Stone{
	float m_weight;
	int m_number;
public:
	Stone(){}
	Stone(float weight, int number) : m_weight(weight), m_number(number){}
	//red 调用了+=,所以this指向red的数据结构。
	Stone operator +=(const Stone &StoneFollowing)
	{
		this->m_number += StoneFollowing.m_number;
		this->m_weight += StoneFollowing.m_weight;
		return *this;
	}
	friend ostream &operator <<(ostream &out, const Stone& ST)
	//2.
	/*friend Stone operator +=(const Stone &StoneBefore, const Stone &StoneFollowing)
	{

		//错误	1	error C2355: “this”: 只能在非静态成员函数或非静态数据成员初始值设定项的内部引用	
		//错误	2	error C2227: “->m_number”的左边必须指向类/结构/联合/泛型类型	

	this->m_number = StoneBefore.m_number + StoneFollowing.m_number;
	this->m_weight = StoneBefore.m_weight + StoneFollowing.m_weight;
	return *this;
	}*/

protected:
};

stone.cpp
friend  &operator <<(ostream &out, const Stone& ST)
	{
		out << ST.m_number << "---" << ST.m_weight << endl;
		return out;
	}

void TestStone()
{
Stone red(20,40);//石头类 中的 红色对象
Stone green(10,5);
Stone allStone;
allStone=red+green;//allStone(30,45)
}

解释下this指针
stone a+=stone b;
Stone operator +=(const Stone &StoneFollowing)
{
a.this->m_number += StoneFollowing(b).m_number;
a.this->m_weight += StoneFollowing(b).m_weight;
return a.*this;
}

为什么用友元:
如果是重载双目操作符(即为类的成员函数),就只要设置一个参数作为右侧运算量,而左侧运算量就是对象本身。。。。。。

而 >> 或<< 左侧运算量是 cin或cout 而不是对象本身,所以不满足后面一点。。。。。。。。就只能申明为友元函数了。。。

如果一定要声明为成员函数,只能成为如下的形式:

ostream & operator<<(ostream &output)

{

return output;

}

所以在运用这个<<运算符时就变为这种形式了:data<<cout;

不合符人的习惯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值