运算符重载+ << ++

重载的意义在于一种新的运算方式,来简化运算方式,重载不可以改变内置的数据运算方式,也不可以混淆常识运算认知

首先是加法运算符的重载,意在实现将类成员属性的直接相加操作

class person
{
public:
	//成员函数重载
	//person operator+(person& a)
	//{
	//	person temp;
	//	temp.a = this->a + a.a;
	//	temp.b = this->b + a.b;
	//	return temp;
	//}

	int a;
	int b;

};
void test01()
{
	person p1;
	p1.a = 10;
	p1.b = 10;
	person p2;
	p2.a = 20;
	p2.b = 20;
	person p3;
	p3 = p1 + p2;//运算符重载;
//成员函数重载本质调用
//  person p3=p1.operator+(p2);
//全局函数本质调用为
//  person p3=p1.qperator+(p2,p3);传参数两个
	cout <<"p3.a==" << p3.a << endl;
	cout <<"p3.b==" << p3.b << endl;
}
person operator+(person & a, person& b)//全局函数重载运算符
{
	person temp;
	temp.a = a.a + b.a;
	temp.b = a.b + b.b;
	return temp;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

全局函数与成员函数都可以实现对加法操作的重载

<<左移运算符的重载

class person
{
	friend ostream& operator<<(ostream& cout, person& p);
public:
	//构造函数
	person(int a, int b)
	{
		m_A = a;
		m_B = b;
	}
private:
	//成员函数重载左移运算符  <<
	// 不会利用成员函数实行重载左移运算符       
	//void operator<<(cout)   调用时  a.operator<<(cout ) --->简化为 a<<cout    无法实现cout在左侧   	
	//{

	//}
	int m_A;
	int m_B;
};
//全局函数重载   
ostream& operator<<(ostream &cout,person &p)  //本质  operator<<(cout,p) -->  简化为 cout << p;
//   cout 的数据类型为   输出流对象  ostream 而且cout 全局 只有一个采用引用的方式传输    
{
	cout << "m_A" << p.m_A << endl << "m_B" << p.m_B;
	return cout;//返回cout 才可以继续进行链式操作
}
void tese01()
{
	person p1(10,10);
	cout << p1<< endl;//链式访问//链式访问需要具备返回值;
}
int main()
{
	tese01();
	system("pause");
	return 0;
}

无法使用成员函数重载左移运算符,在类内调用成员函数//void operator<<(cout)   调用时  a.operator<<(cout ) --->简化为 a<<cout    输出值在左侧,无法实现cout在左侧 

且最后返回值cout为 ostream&,原因是在整个程序内部值存在一个cout。返回cout是因为在左移运算时链式访问需要具备返回值才能进行后续左移运算,否则只能运行一条语句。

自定义类型的定义和加加运算的重载

class MyInteger //自定义整型变量
{
	friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
	MyInteger()
	{
		m_num = 0;
	}
	//重载前置++运算符
	 MyInteger& operator++()//返回引用原因 确保每一次都是对自身进行++  前后始终一个值
	{
		m_num++;//先操作
		return *this;//指向自身地址 解引用返回自身值
	}
	//重载后置++运算符
	 MyInteger operator++(int)//函数重载  int表示占位参数,可以用来区分前置后置递增
	 {
		 //先记录结果
		 MyInteger temp = *this;
		 //后 递增
		 m_num++;
		 //将记录结果返回
		 return temp;//返回值  不返回引用  返回的是局部对象的引用
	 }
private:
	int m_num;
};
//重载左运算符
ostream& operator<<(ostream& cout,MyInteger myint)//先做左移运算再++
{
	cout << myint.m_num;
	return cout;//全局只有一个
}
void test01()
{
	MyInteger myint;
	cout << ++myint << endl;
	cout << myint << endl;
	cout << myint++ << endl;
	cout << myint << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

在做++ 运算前先重载<<运算使其可以操作自定义类型myint,++操作分为前置++和后置++

对于同一运算两种不同操作方式涉及到operator()的重定义所以在第二个operator(int)占位符来区分

采用引用的方式来修改函数值是保证每一次都是对自身函数进行++操作,即可实现重载操作。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值