调用时机
使用一个已经创建完的对象来初始化一个新对象
class Person { public: Person() { cout << "Person()构造" << endl; } ~Person() { cout << "~Person()析构" << endl; } Person(const Person &p) { cout << "Person()拷贝构造" << endl; this->name = p.name; this->age = p.age; } private: string name; int age; }; int main() { Person p1; Person p2 = p1; return 0; }
Person()构造 Person()拷贝构造 ~Person()析构 ~Person()析构
值传递的方式给函数传参
class Person { public: Person() { cout << "Person()构造" << endl; } ~Person() { cout << "~Person()析构" << endl; } Person(const Person &p) { cout << "Person()拷贝构造" << endl; this->name = p.name; this->age = p.age; } void test(Person p){} private: string name; int age; }; int main() { Person p1; Person p2; p2.test(p1); return 0; }
Person()构造 Person()构造 Person()拷贝构造 ~Person()析构 ~Person()析构 ~Person()析构
以值方式返回局部对象
class Person { public: Person() { cout << "Person()构造" << endl; } ~Person() { cout << "~Person()析构" << endl; } Person(const Person &p) { cout << "Person()拷贝构造" << endl; this->name = p.name; this->age = p.age; } Person test() { return *this; } private: string name; int age; }; int main() { Person p1; Person p2 = p1.test(); return 0; }
Person()构造 Person()拷贝构造 ~Person()析构 ~Person()析构