C++之++运算符重载问题

记录++之前先记一下左右值和存取数据的问题

数据的存放分三个部分,堆区,栈区和静态变量区

左值可以更改,右值不能更改

栈区和堆区存储的都是左值,可以随意更改其值,静态变量区部分数据是右值,比如const修饰的值,函数创建的临时变量,都不可更改

前缀++重载,直接直接++操作,返回本身即可

后缀++重载,需创建临时变量,对原元素执行+1操作,返回临时变量,返回值类型用const修饰,让返回值成为一个右值,不可修改,防止出现(++(class++))的情况

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 class cl{
 4 public:
 5     int x;
 6     cl(){}
 7     cl(const cl& c){
 8         cout<<"执行复制构造函数\n";
 9         x=c.x;
10     }
11     cl& operator++(){//前缀++重载
12         x+=3;
13         return *this;
14     }
15     const cl operator++(int ){//后缀++重载
16         cl mid = *this;
17         this->x+=2;
18         return mid;
19     }
20     void prin(){
21         cout<<"cl x = "<<x<<endl;
22     }
23 };
24 
25 int func()
26 {
27     int x=1;
28     return x;
29 }
30 int main()
31 {
32     cl c1;
33     c1.x=0;
34     cl c2=(c1++);
35     cout<<c1.x<<" "<<c2.x<<"\n";
36 
37     int a=10;
38     int x=(++(a++));//报错,a++产生的临时变量是右值,不可改变
39     
40     return 0;
41 }

猜你喜欢

转载自www.cnblogs.com/wa007/p/9380184.html