C++深拷贝的浅拷贝

发布时间 2023-04-12 01:46:54作者: boyboy!

 

  • class  person
    {
    public:
    person(int age,int height)
    {
    m_age=age;
    m_height=new int(height);//new一个堆区接受外来值与成员变量地址一致
    cout<<"有参构造函数"<<endl;
    }
    ~person()//析构函数将堆区的数据释放
    {
    if(m_height!=NULL)
    {
    delete m_height;
    m_height=NULL;
    }
    cout<<"析构函数"<<endl;
    }
    int m_age;
    int *m_height;
    };
    void text01()
    {
    person p1(10,20);
    cout<<"年龄为"<<p1.m_age<<"身高为"<<p1.m_height<<endl;
    person p2(p1);
    cout<<"年龄为"<<p2.m_age<<"身高为"<<p2.m_height<<endl;
    }
    int main()
    text01();
  • 当调用析构函数时由于,p2的拷贝函数和p2的构造函数同时对同一份地址进行析构产生错误

  • 修改系统自动给出的拷贝构造,在有参构造下应自己实现拷贝构造函数

  • //深拷贝
    person(const person *p)
    {
    //m_height=p.m_height;系统自动给出
    m_height=new int (*p.m_height);
    }

初始化列表

  • class person
    {
    public:
    person(int a,int b,int c):m_a(a),m_b(b),m_c(c)
    {}
    int m_a;
    int m_b;
    int m_c;
    };
    void text01()
    {
    person p(10,25,66);
    cout<<p.m_a<<p.m_b<<p.m_c<<endl;
    }
    int main()
    text01();
  • 类对象作为类成员

    • class phone
      {
      public:
      phone(string pname)
      {
      m_pname=pname;
      }
      string m_pname;
      };
      class person
      {
      public:
      person(string name,string pname):m_name(name),m_pname(pname)
      {}
      string m_name;
      phone m_pname;
      };
      void test()
      {
      person p("小子","苹果max");
      cout<<"姓名"<<p.m_name<<"手机为"<<p.m_pname.m_pname<<endl;
      }
      int main()
      {
      test();
      }
  • 静态成员

    • class person
      {
      public:
      static int age;//类内声明
      private:
      };
      int person::age=10;// 类外初始化
      void text01()
      {
      //用对象进行访问
      person p1;
      cout<<p1.age<<endl; //输出的结果是10
      person p2;
      cout<<p2.age<<endl;//输出的结果是10
      //通过类名进行访问
      cout<<person::age<<endl;
      }
      int main()
      {
      text01();
      system("pause");
      return 0;
      }
    •