您好,登錄后才能下訂單哦!
有三種情況會產(chǎn)生復(fù)制構(gòu)造函數(shù)的調(diào)用!
在代碼中只要產(chǎn)生臨時對象都會調(diào)用復(fù)制構(gòu)造函數(shù)!
在代碼中顯示
#include<iostream>
using namespace std;
class Location{
public:
Location(int a, int b){ x = a; y = b; }
Location( const Location& lc){
cout << "call copy_constructor" << endl;
x = lc.getx();//這里必須把getx()設(shè)為常量函數(shù)才可以被調(diào)用
y = lc.y;
}
~Location(){
cout << "object destroyed" << endl;
}
int getx()const{//只有定義為常函數(shù)才可以被常量對象使用
return x;
}
int gety()const{
return y;
}
void setx(int a){ x = a; }
void sety(int b){ y = b; }
private:
int x, y;
};
void f(Location p){//1.這里會產(chǎn)生調(diào)用復(fù)制構(gòu)造函數(shù)!因為需要產(chǎn)生臨時對象
p.setx(5);
p.sety(6);
cout << "x=" << p.getx() << " y=" << p.gety() << endl;
}
Location g(){//2.這里會產(chǎn)生調(diào)用復(fù)制構(gòu)造函數(shù)
Location p(4, 5);
return p;
}
Location& h(){//這里是引用所以不產(chǎn)生臨時對象,所以不調(diào)用復(fù)制構(gòu)造函數(shù)
cout << "h()" << endl;
Location p(4, 6);
return p;
}
void func(){
Location location1(2, 3);
Location location2 = location1;//3.這里也產(chǎn)生調(diào)用復(fù)制構(gòu)造函數(shù)
cout << "location.x=" << location2.getx() << endl;
cout << "location.y=" << location2.gety() << endl;
f(location2);
cout << "location.y=" << location2.gety() << endl;
location2 = g();
cout << "location.y=" << location2.gety() << endl;
location2 = h();
}
int main(){
func();//作用是使得所有的對象都可以析構(gòu)!
system("pause");
return 0;
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。