学习总结(不知道对错)
构造函数:从无到有创建一个对象;
拷贝构造函数:在已有对象基础A基础上,把A拷贝一份,创建一个新对象,比如取名字B,(为什么不直接叫做对象拷贝函数?)
例子1:
#include<iostream> using namespace std; class Rect { public: Rect() { count++; } ~Rect() { cout << this << endl; count--; } static int getCount() { return count; } private: int width; int height; static int count; }; int Rect::count = 0; int main() { Rect rect1; cout << "The count of Rect:" << Rect::getCount() << endl; Rect rect2(rect1); cout << "The count of Rect:" << Rect::getCount() << endl; return 0; }
Rect rect2(rect1)这句代码,拷贝得到一个新对象,调用的是拷贝构造函数,实现里没有给计数变量加+1,
所以在main函数里两个打印都是1.
#include<iostream> using namespace std; class Rect { public: Rect() { count++; } Rect(const Rect& r) { width=r.width; height=r.height; count++; } ~Rect() { count--; } static int getCount() { return count; } private: int width; int height; static int count; }; int Rect::count=0; int main() { Rect rect1; cout<<"The count of Rect:"<<Rect::getCount()<<endl; Rect rect2(rect1); cout<<"The count of Rect:"<<Rect::getCount()<<endl; return 0; }
要改成这个样子滴,动动拷贝构造函数