拷贝构造函数除公认的注意事项以外,还需注意:
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "no pragma" << endl;
}
Person(int a)
{
age = a;
cout<<"yes pragma:" << age <<endl;
}
Person(const Person &p)
{
age = p.age;
cout << "copy yes pragma:" << age << endl;
}
private:
int age;
};
int main()
{
Person p1; //与 Person(); 一样
Person p2(10); //与 Person(10); 一样
Person p3 = p2;
}
1. Person()无参构造函数直接调用,与通过实例化对象调用,输出结果一致。
2. 拷贝构造函数必须通过实例化对象来调用;
结果如下:

本文探讨了C++中的拷贝构造函数,强调其必须通过对象实例调用来触发,并通过示例展示了无参构造函数、带有参数的构造函数和拷贝构造函数的使用。在程序中,拷贝构造函数用于初始化新对象为已有对象的副本,输出结果显示了拷贝构造函数的调用过程。

被折叠的 条评论
为什么被折叠?



