加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:49:42 所属栏目:百科 来源:网络整理
导读:#include using namespace std; class Test { public: Test() {}; Test(int a) { m_a = a; } Test operator++() //重载前置++运算符 { ++m_a; return *this; //引用返回 } Test operator++(int) //站位参数在这里有点用,用来区分重载前置运算符和后置运算符

#include

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

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修饰

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读