分析测试百科网

搜索

喜欢作者

微信支付微信支付
×

C++之拷贝构造函数的浅copy和深copy(二)

2020.9.28
头像

王辉

致力于为分析测试行业奉献终身

(3)注意:

在写程序的时候,定义的类对象初始化时看属于哪种类型的:

Test t;//对应无参构造函数
Test t(1);//对应有参构造函数
Test t1;
Test t2=t1;//对应拷贝构造函数

比如下面我定义的类对象属于无参构造函数(当然前提是你手写了其他构造函数,虽然说编译器会默认提供,但是既然要手写,那么三种构造函数就在定义类对象的时候按需求来写),如果只写了有参数构造函数,那么编译器就会报错:

#include <iostream>
#include <string>
class Test{
private:
  int i;
  int j;
public:
 Test(int a)
 {
    i = 9;
    j=8;
 }
 Test(const Test& p)
  {
     i = p.i;
     j = p.j;
  }
};
int main()

  Test t;
 return 0;

输出结果:

root@txp-virtual-machine:/home/txp# g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:25:9: error: no matching function for call to ‘Test::Test()’
   Test t;
        ^
test.cpp:25:9: note: candidates are:
test.cpp:15:3: note: Test::Test(const Test&)
  Test(const Test& p)
  ^
test.cpp:15:3: note:   candidate expects 1 argument, 0 provided
test.cpp:10:3: note: Test::Test(int)
  Test(int a)
  ^
test.cpp:10:3: note:   candidate expects 1 argument, 0 provided

4、拷贝构造函数的意义:

(1)浅拷贝

拷贝后对象的物理状态相同

(2)深拷贝

拷贝后对象的逻辑状态相同

(3)编译器提供的拷贝构造函数只进行浅拷贝

代码版本一:

#include <stdio.h>
#include <string>
class Test{
private:
  int i;
  int j;
  int *p;
public:
  int getI()
  {
     return i;
  }
  int getJ()
  {
     return j;
  }
  int *getP()
  {
     return p;
  }
  Test(int a)
  {
     i = 2;
     j = 3;
     p = new int;
     *p = a;
 }
 void free()
 {
   delete p;
 }
};
int main()

  Test t1(3);//Test t1 3;
  Test t2 = t1;
 printf("t1.i = %d, t1.j = %d, t1.p = %p", t1.getI(), t1.getJ(), t1.getP());
 printf("t2.i = %d, t2.j = %d, t2.p = %p", t2.getI(), t2.getJ(), t2.getP());
  t1.free();
  t2.free();
 
  return 0;


互联网
仪器推荐
文章推荐