编程语言
首页 > 编程语言> > C++拷贝构造

C++拷贝构造

作者:互联网

调用时机

使用一个已经创建完的对象来初始化一个新对象

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()析构

标签:p1,name,int,age,构造,Person,C++,析构,拷贝
来源: https://www.cnblogs.com/zhangxuechao/p/15973975.html