天天看點

copy_constructor 複制構造函數

有三種情況會産生複制構造函數的調用!

在代碼中隻要産生臨時對象都會調用複制構造函數!

在代碼中顯示

#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()設為常量函數才可以被調用

y = lc.y;

}

~Location(){

cout << "object destroyed" << endl;

int getx()const{//隻有定義為常函數才可以被常量對象使用

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.這裡會産生調用複制構造函數!因為需要産生臨時對象

p.setx(5); 

p.sety(6);

cout << "x=" << p.getx() << " y=" << p.gety() << endl;

Location g(){//2.這裡會産生調用複制構造函數

Location p(4, 5);

return p;

Location& h(){//這裡是引用是以不産生臨時對象,是以不調用複制構造函數

cout << "h()" << endl;

Location p(4, 6);

void func(){

Location location1(2, 3);

Location location2 = location1;//3.這裡也産生調用複制構造函數

cout << "location.x=" << location2.getx() << endl;

cout << "location.y=" << location2.gety() << endl;

f(location2);

location2 = g();

location2 = h();

int main(){

func();//作用是使得所有的對象都可以析構!

system("pause");

return 0;

本文轉自 神迹難覓 51CTO部落格,原文連結:http://blog.51cto.com/ji123/1919408,如需轉載請自行聯系原作者