本文共 1811 字,大约阅读时间需要 6 分钟。
参考代码:
#includeusing namespace std;int testIntRef(){ int i=1; int &ri = i ; int j = i ; cout << hex << "Addr of i: " << &i << endl; cout << hex << "Addr of ri:" << &ri << endl ; cout << hex << "Addr of j: " << &j << endl ; return 0;}int testObjectRef(){ class A{ public: int ma1,ma2 ; A(int a1 , int a2){ ma1 = a1 ; ma2 = a2 ; } }; A a(1,2) ; A& ra = a ; A b =a ; cout << hex << "Addr of a: " << &a << endl; cout << hex << "Addr of ra:" << &ra << endl ; cout << hex << "Addr of b: " << &b << endl ; return 0 ;}class H{public: int mh1 , mh2 ; H(int h1 , int h2) { mh1 = h1 ; mh2 = h2 ; }};void callByRefAndValue( H& rh , H h ){ cout << hex << "Addr of rh:" << &rh << endl ; cout << hex << "Addr of h: " << &h << endl ;}int testCallByRefAndValue(){ H h(1,2) ; cout << hex << "Addr of h outer: " << &h << endl ; callByRefAndValue( h , h ) ; return 0;}H& returnRefOfEnterRef(H& hh ){ cout<<"in returnRefOfEnterRef :"< << &hh << endl ; return hh ;}H& returnRefOfEnterVal(H hh ){ cout<<"in returnRefOfEnterVal :"< << &hh << endl ; return hh ;}H returnValOfEnterRef(H& hh ){ cout<<"in returnValOfEnterRef :"< << &hh << endl ; return hh ;}int testReturnRef(){ H h(1,2) ; cout<<"h inializted:"< << &h << endl ; H& h1 = returnRefOfEnterRef( h ) ; cout<<"Get from returnRefOfEnterRef :"< << &h1 << endl ; H& h2 = returnRefOfEnterVal( h ) ; cout<<"Get from returnRefOfEnterVal :"< << &h2 << endl ; H h3 = returnValOfEnterRef( h ) ; cout<<"Get from returnValOfEnterRef :"< << &h3 << endl ;}int main(){ //testIntRef() ; //testObjectRef() ; //testCallByRefAndValue(); testReturnRef();}
转载地址:http://zemqf.baihongyu.com/