C++前置++和后置++运算符重载

版权声明: https://blog.csdn.net/qq_40794602/article/details/85223789
#include<iostream>
using namespace std;

class Test
{
public:
	Test() {};
	Test(int a)
	{
		m_a = a;
	}
	Test& operator++()  //重载前置++运算符
	{
		++m_a;
		return *this;  //引用返回
	}

	Test operator++(int) //站位参数在这里有点用,用来区分重载前置运算符和后置运算符
	{
		Test temp = *this; //保存原始数据
		m_a++;
		return temp;  //将原数据按值返回,切记不是引用返回
	}
	int m_a;
};

ostream& operator<<(ostream &cout, Test t) //这里Test为什么不加引用?因为重置后置++运算符的时候,是值返回类型的,可以理解为一个常量吧,后面的代码我会具体解释
{
	cout << t.m_a;
	return cout;
}

int main()
{
	Test t1(1);
	cout << "测试前置运算符:" << ++t1 << endl;
	//cout << "测试后置运算符:" << t1++ << endl;  //这句报错
	cout << "查看值:" << t1.m_a << endl;
	return 0;
}

上面留下了一个问题,为什么重载<<运算符的时候,Test的参数不设置为引用?

#include<iostream>
using namespace std;

int test1()
{
	int a = 1;
	return a;  //注意这里是值返回
}

void test2(int &b)
{
	cout << b << endl;
}

int main()
{
	int c = 1;
	test2(test1());  //报错
	return 0;
}
//这段程序报错--无法将参数 1 从“int”转换为“int &”

可以理解为,值返回的不是一个合法空间,就不可以使用引用,但是有两种解决办法:

  • 不使用引用
  • 将test2的参数使用const修饰

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/85223789