有三种情况会产生复制构造函数的调用!

在代码中只要产生临时对象都会调用复制构造函数

在代码中显示

#include

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);

return p;

}

void func(){

Location location1(2, 3);

Location location2 = location1;//3.这里也产生调用复制构造函数


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();//作用是使得所有的对象都可以析构!

system("pause");

return 0;

}