如何在C ++中实现副本构造函数?

在这里,我们将看到如何在C ++中实现副本构造函数。在讨论之前,我们应该知道什么是复制构造函数。

拷贝构造是通过用相同的类,它已先前创建的一个目的初始化它创建了一个对象的构造。复制构造函数用于-

  • 从另一个相同类型的对象初始化一个对象。

  • 复制对象以将其作为参数传递给函数。

  • 复制对象以从函数返回它。

如果未在类中定义副本构造函数,则编译器本身将定义一个。如果该类具有指针变量并具有一些动态内存分配,则必须具有副本构造函数。复制构造函数的最常见形式如下所示:

classname (const classname &obj) {
//构造函数的主体
}

此处,obj是对用于初始化另一个对象的对象的引用。

示例

#include <iostream>
using namespace std;
class Line {
   public:
      int getLength( void );
      Line( int len ); // simple constructor
      Line( const Line &obj); // copy constructor
      ~Line(); // destructor
   private:
      int *ptr;
};
//成员函数定义,包括构造函数
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;
   //为指针分配内存;
   ptr = new int;
   *ptr = len;
}
Line::Line(const Line &obj) {
   cout << "复制分配ptr的构造函数。" << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}
Line::~Line(void) {
   cout << "释放内存!" << endl;
   delete ptr;
}
int Line::getLength( void ) {
   return *ptr;
}
void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}
//程序的主要功能
int main() {
   Line line(10);
   display(line);
   return 0;
}

输出结果

Normal constructor allocating ptr
复制分配ptr的构造函数。
Length of line : 10
释放内存!
释放内存!

让我们看一下相同的示例,但只需要很小的改动即可使用相同类型的现有对象创建另一个对象-

示例

#include <iostream>
using namespace std;
class Line {
   public:
      int getLength( void );
      Line( int len ); // simple constructor
      Line( const Line &obj); // copy constructor
      ~Line(); // destructor
   private:
      int *ptr;
};
//成员函数定义,包括构造函数
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;
   //为指针分配内存;
   ptr = new int;
   *ptr = len;
}
Line::Line(const Line &obj) {
   cout << "复制分配ptr的构造函数。" << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}
Line::~Line(void) {
   cout << "释放内存!" << endl;
   delete ptr;
}
int Line::getLength( void ) {
   return *ptr;
}
void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}
//程序的主要功能
int main() {
   Line line1(10);
   Line line2 = line1; // This also calls copy constructor
   display(line1);
   display(line2);
   return 0;
}

输出结果

Normal constructor allocating ptr
复制分配ptr的构造函数。
复制分配ptr的构造函数。
Length of line : 10
释放内存!
复制分配ptr的构造函数。
Length of line : 10
释放内存!
释放内存!
释放内存!