拷贝构造函数的用途
拷贝构造函数,它由编译器调用来完成一些基于同一类的其他对象的构建及初始化。其唯一的形参必须是引用,但并不限制为const,一般普遍的会加上const限制。
拷贝构造函数发生的时机
1,用一个对象初始化另一个对象
Cat c1();
Cat c2(c1);
2,函数按值传递 (实参--->形参)
3,函数返回对象
默认拷贝构造函数
如果程序员不提供拷贝构造函数,编译器会提供默认的拷贝构造函数,将对应的数据成员逐一赋值。(默认拷贝构造函数不能用于2种特殊情况,程序员必修提供拷贝构造函数)
2种特殊情况
//Aircraft.h #include<string> #include<iostream> class Aircraft { private: static int count;//飞行器的总量 std::string color;//飞行器的颜色 public: Aircraft(const std::string &color); Aircraft(const Aircraft &A); ~Aircraft(); static int getCount();//静态成员不允许使用const };
//Aircraft.cpp #include<string> #include<iostream> #include"Aircraft.h" using namespace std; int Aircraft::count = 0; Aircraft::Aircraft(const string &color) { ++count; this->color = color; cout << color << " is created\n"; } Aircraft::Aircraft(const Aircraft &A) { ++count; color = A.color; cout << color << " copy\n"; } Aircraft::~Aircraft() { --count; cout << color << " is destroied\n"; } int Aircraft::getCount() { return count; }
//main #include<cstdlib> #include<string.h> #include<iostream> #include"Aircraft.h" using namespace std; int main() { cout << "count is " << Aircraft::getCount() << endl; Aircraft a("red"); cout << "count is " << Aircraft::getCount() << endl; Aircraft b = a; cout << "count is " << Aircraft::getCount() << endl; Aircraft *c = new Aircraft("black"); cout << "count is " << Aircraft::getCount() << endl; delete c; { Aircraft d("orange"); cout << "count is " << Aircraft::getCount() << endl; } cout << "count is " << Aircraft::getCount() << endl; system("pause"); }
count is 0
red is created
count is 1
red copy
count is 2
black is created
count is 3
black is destroied
orange is created
count is 3
orange is destroied
count is 2
请按任意键继续. . .
//深拷贝 class Store { private: int count; int *p; public: Store() {//构造函数 count = 10; p = new int[10]; }//拷贝构造函数 Store(const Store &S) { count = S.count; p = new int[10]; for (int i = 0; i < 10;++i) { p[i] = S.p[i]; } }//析构函数 ~Store() { delete[] p; } };
拷贝构造函数和重载的“=”
指针的值被复制了,但指针所指内容并未被复制。包含动态分配成员的类除提供拷贝构造函数外,还应该考虑重载"="赋值操作符号。
"="在对象声明语句中,表示初始化,这种初始化也可用圆括号表示。
"="表示赋值操作。将对象theObjone的内容复制到对象theObjthree,这其中涉及到对象theObjthree原有内容的丢弃,新内容的复制。
cat c2 = c1;会调用拷贝构造函数。
c2 = c1;调用的却是重载的“=”运算符。