概念
- 只有一个参数,即同类对象的引用
X::X(X&)
或X::X(const X&)
常引用更常用- 系统会生成默认复制构造函数,完成浅复制功能
- 若自己定义复制构造函数,则默认那个就没得了
起作用的三种情况
- 当用一个对象去初始化另一个对象
classname object1(object2)
classname object1 = object2
这是初始化语句,不是赋值- 参数是类A的对象,invoking时,则类A的复制构造函数将被调用
void func(A a1)
,所有类对象都要被初始化,这个初始化时将调用copy constructor function(开销会比较大,所以一般考虑常量引用参数)- 返回值是类A对象,则返回时复制构造函数被调用。
ATTENDTION
- 对象间赋值并不导致复制构造函数调用(若不是初始化就是赋值)
Example
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class student
{
private:
string name;
char* hobby;
int age;
public:
student(string n="no",char h[]=nullptr,int a=0);
student(const student& s);
~student();
void displace();
} ;
student::student(string n,char h[],int a):name(n),age(a)
{
hobby = new char[strlen(h)+1];
strcpy(hobby,h);
}
student::student(const student& s):name(s.name),age(s.age)
{
hobby = new char[strlen(s.hobby)+1];
strcpy(hobby,s.hobby);
}
student::~student()
{
delete [] hobby;
}
void student::displace()
{
cout<<name<<" is "<<age<<" years old and good at "
<<hobby<<endl;
}
int main()
{
student s2("Jeff","studying",20),s3("Alice","talking",18)
,s1=s2;
s2.displace();
s3.displace();
cout<<"S1 as followed: "<<endl;
s1.displace();
}
ps.如果有动态分配内存的,一定要析构函数delete