在 C++ 中,何时调用复制构造函数?


复制构造函数是一种使用此前已创建的同类对象来初始化对象而创建对象的构造函数。复制构造函数用于 −

  • 用一个同类型对象初始化另一个同类型对象。
  • 将一个对象复制为一个函数的参数。
  • 将一个对象复制为一个函数的返回值。

如果没有在类中定义复制构造函数,编译器会自行定义一个。如果该类有指针变量,并进行了一些动态内存分配,那么必须有一个复制构造函数。最常见的复制构造函数形式如下 −

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!

更新于: 2019-07-30

814 次浏览

启动你的 职业

完成该课程以取得认证

开始学习
广告
© . All rights reserved.