【C++】复制构造函数
生活随笔
收集整理的這篇文章主要介紹了
【C++】复制构造函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
參考資料:黃邦勇帥(里面對于臨時(shí)變量的說法我不是很理解,感覺里面的解釋有問題)
?
用到復(fù)制構(gòu)造函數(shù)的情況:
1.函數(shù)值傳遞
2.返回對象
3.用一個(gè)對象初始化另一個(gè)對象
?
重點(diǎn)注意下面兩種情況:
① 只調(diào)用復(fù)制構(gòu)造函數(shù),不會(huì)生成臨時(shí)變量
A a = b;
② 會(huì)產(chǎn)生臨時(shí)變量,會(huì)調(diào)用復(fù)制構(gòu)造函數(shù)和賦值函數(shù)
A a;
a = A(b);
?
#include<iostream> using namespace std;class hyong { public:int a, b, c;hyong(){a = b = c = 0;cout << "construct" <<endl;}hyong(int i){a = b = c = i;cout << "construct 2" <<endl;}hyong(const hyong &obj) //復(fù)制構(gòu)造函數(shù) {a = b = c = 9;cout << "construct copy" <<endl;}void h(hyong k) //值傳遞 {cout << "k.a = " << k.a << " k.b = " << k.b<< endl;}hyong & hyong::operator = (const hyong & other){cout << "=" << endl;if(this == &other)return *this;a = other.a;b = other.b;c = other.c;return *this;}~hyong(){cout << "xigou" << endl;} };hyong f() //返回對象 {hyong m3(5);return m3; }int main() {hyong m(1);hyong n = m; //調(diào)用復(fù)制構(gòu)造函數(shù)cout << m.a << m.b << endl;cout << n.a << n.b << endl;hyong m1 = hyong(m); //調(diào)用復(fù)制構(gòu)造函數(shù)cout << m1.a << m1.b << endl;hyong m2(m); //調(diào)用復(fù)制構(gòu)造函數(shù)cout << m2.a << m2.b << endl;hyong *p = new hyong(m); //調(diào)用復(fù)制構(gòu)造函數(shù)cout << p->a << p->b << endl;cout << "------------"<< endl;hyong m3;m3 = hyong(m); //先用復(fù)制構(gòu)造函數(shù)得到了一個(gè)臨時(shí)變量,然后用賦值函數(shù)將臨時(shí)變量值賦給m3, 之后臨時(shí)變量析構(gòu)cout << "------------"<< endl;hyong m4;m4 = m; //直接調(diào)用賦值cout << "------------"<< endl;hyong m5 = f(); // 設(shè)f()返回的臨時(shí)變量為r,其實(shí)r就是函數(shù)里的m3,//m3通過復(fù)制構(gòu)造函數(shù)賦給m5,之后m3析構(gòu)cout << "------------"<< endl;hyong m6; //先定義,并用默認(rèn)構(gòu)造函數(shù)初始化了m6m6 = f(); //f()返回m3, 然后用復(fù)制構(gòu)造函數(shù)將m3賦給了臨時(shí)變量tmp, m3析構(gòu);//tmp通過賦值函數(shù)賦給m6, tmp析構(gòu)cout << "------------"<< endl;hyong m7(f()); // 設(shè)f()返回m3,m3通過復(fù)制構(gòu)造函數(shù)賦給m7,之后m3析構(gòu)return 0; }轉(zhuǎn)載于:https://www.cnblogs.com/dplearning/p/4783626.html
總結(jié)
以上是生活随笔為你收集整理的【C++】复制构造函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 转盘轴承和转台轴承有哪些区别
- 下一篇: cocos2x (c++/lua) sp