C++之++運算子多載問題

來源:互聯網
上載者:User

標籤:變數   +=   運算   修改   void   部分   ++   amp   靜態   

 

記錄++之前先記一下左右值和存取資料的問題

資料的存放分三個部分,堆區,棧區和靜態變數區

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

棧區和堆區儲存的都是左值,可以隨意更改其值,靜態變數區部分資料是右值,比如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 }

 

C++之++運算子多載問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.