重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

copy_constructor复制构造函数

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

创新互联专注于蓬溪网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供蓬溪营销型网站建设,蓬溪网站制作、蓬溪网页设计、蓬溪网站官网定制、小程序开发服务,打造蓬溪网络公司原创品牌,更为您提供蓬溪网站排名全网营销落地服务。

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

在代码中显示

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

}


分享文章:copy_constructor复制构造函数
当前URL:http://cqcxhl.cn/article/jjihhe.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP