極其重要的分析

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   div   問題   sp   log   

#include <iostream>using namespace std;class a{    public:        a(){            value ++;            cout <<"default a"<<endl;        }        a(const a&){            value ++;            cout <<"const a"<<endl;        }        a operator=(const a& a1){            cout <<"operator ="<<endl;            return a(a1);        }        void f(){            cout <<"value is "<<value <<endl;        }        ~a(){            cout <<"~a"<<endl;        }    private:        static    int value;};int a::value = 0;void f1(a a1){    a1.f();    cout <<"f1"<<endl;}a f2(){    cout <<"f2"<<endl;    return a();}void f3(){    a a1,a2;    f1(a1);    a2 = f2();}int main(){    f3();    return 0;}

結果是

default a  f3內的a1調用建構函式
default a  f3內的a2調用建構函式
const a   f1內的的a變數以a1為參數調用建構函式
value is 3  此時有三個a對象了,所以value為3
f1      列印輸出f1
~a      f1內的的局部變數退出了範圍,此時調用解構函式
f2      f2內列印輸出f2
default a  f2調用預設建構函式
operator =  f2在f3內因為調用=這個運算子,所以才會列印輸出
const a
~a
~a
~a
~a



這個其實有問題的,一般而言,有賦值的必須返回*this(=,+=,-=等等)

類似下面這個



#include <iostream>using namespace std;class a{    public:        a(){            value ++;            cout <<"default a"<<endl;        }        a(const a&){            value ++;            cout <<"const a"<<endl;        }        a& operator=(const a& a1){            cout <<"operator ="<<endl;            return *this;        }        void f(){            cout <<"value is "<<value <<endl;        }        ~a(){            cout <<"~a"<<endl;        }    private:        static    int value;};int a::value = 0;void f1(a a1){    a1.f();    cout <<"f1"<<endl;}a f2(){    cout <<"f2"<<endl;    return a();}void f3(){    a a1,a2;    f1(a1);    a2 = f2();}int main(){    f3();    return 0;}


  4 class a{  5     public:  6         a(int i):value(i){}  7         ~a(){cout <<"~a"<<endl;}  8         a& operator=(const a& a1){  9             this->value = a1.value; 10             return *this; 11         } 12         int get(){return value;} 13     private: 14         int value; 15 };

最好的方法,=,+=,-=,等等這些符號絕對不能導致建構函式,

記住此時

a a1=10;

此時調用的是建構函式雖然用的符號是=這個符號,這一點必須高清晰

 

結果為

 

default a
default a
const a
value is 3
f1
~a
f2
default a

operator =
~a
~a
~a

 

 

極其重要的分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.