Skip to content
On this page

CPP_拷贝构造函数


标签:CPP/面向对象  

拷贝构造函数

功能:使用一个类对象对另一个类对象进行初始化的工作

cpp
// 以下都是拷贝构造函数
string s1("hello world");
string s2(s1);
string s3 = s1;
string s4{s1};

格式

  • 与类同名
  • 无返回值
  • 参数:同类或者其他对象的引用
  • public 权限
cpp
Stu(const Stu &outher): name(other.name), age(other.age);
  • 拷贝指针成员的时候,(一般)需要进行深拷贝
cpp
Stu(const Stu &outher): name(other.name), age(other.age),
                        score(new double(*(other.score));

Last updated: