温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

copy_constructor 复制构造函数

发布时间:2020-08-12 20:03:22 来源:网络 阅读:264 作者:神迹难觅 栏目:编程语言

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

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

在代码中显示

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

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;

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI