当前位置: 首页 > 文档资料 > C++ 中文教程 >

复制构造函数(Copy Constructor)

优质
小牛编辑
131浏览
2023-12-01

copy constructor是一个构造函数,它通过使用先前创建的同一类的对象初始化它来创建对象。 复制构造函数用于 -

  • 从另一个相同类型的对象初始化。
  • 复制对象以将其作为参数传递给函数。
  • 复制对象以从函数返回它。

如果没有在类中定义复制构造函数,则编译器本身定义一个。如果该类具有指针变量并具有一些动态内存分配,则必须具有复制构造函数。 这里显示了最常见的复制构造函数形式 -

classname (const classname &obj) {
   // body of constructor
}

这里, 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;
};
// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;
   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}
Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}
Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}
int Line::getLength( void ) {
   return *ptr;
}
void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main() {
   Line line(10);
   display(line);
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!

让我们看一下相同的例子,但是使用相同类型的现有对象进行一些小改动来创建另一个对象 -

#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;
};
// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;
   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}
Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}
Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}
int Line::getLength( void ) {
   return *ptr;
}
void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main() {
   Line line1(10);
   Line line2 = line1; // This also calls copy constructor
   display(line1);
   display(line2);
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!