类与对象之拷贝构造函数的调用


emmmm,这一篇是对之前一章构造函数的补充。

拷贝构造函数

​ 拷贝构造函数也是一种重载版本的构造函数,它是用一个已存在的对象初始化另一个新创建的同类对象。该函数的参数与普通构造函数不同,是一个同类的常引用。高效地传递对象,也能保证原对象不被修改。

类名(const 类名&对象名);

实例:

class Person
{
public:

Person(){
cout << "默认构造函数。\n";
}
Person(int a)
{
age = a;
cout << "有参构造函数。\n";
}
Person(const Person& p)
{
cout << "拷贝构造函数。\n";
age = p.age;

}
~Person()
{
cout << "析构函数。\n";
}

int age;
};
//使用一个已经创建完毕的对象来初始化一个新对象
void test01()
{
Person p1(10);
Person p2(p1);
cout << "p2的年龄:" <<p2.age << endl;

}
//值传递的方式给函数参数传值
void dowork(Person p)
{
cout <<"年龄:" << p.age << endl;;
}
void test02()
{
Person p(10);
dowork(p);

}
//值方式返回局部变量
Person dowork2()
{
Person p1(10);
cout << (int*)&p1 << endl;
cout << "年龄:" << p1.age << endl;
return Person(p1);
}
void test03()
{
Person p = dowork2();
cout << (int*)&p << endl;
}
int main()
{
test01();
test02();
test03();
return 0;
}
  • 使用一个已经创建完毕的对象来初始化一个新对象
有参构造函数。
拷贝构造函数。
p2的年龄:10
析构函数。
析构函数。
  • 值传递的方式给函数参数传值
有参构造函数。
拷贝构造函数。
年龄:10
析构函数。
析构函数。
  • 值方式返回局部变量
有参构造函数。
000000DB556FF364
年龄:10
拷贝构造函数。
析构函数。
000000DB556FF4A4
析构函数。

Author: T1g3r
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source T1g3r !
评论
  TOC