c++ 中的复制构造函数如何工作

How Does the copy constructor in c++ work?

本文关键字:工作 何工作 复制 构造函数 c++      更新时间:2023-10-16

当我将"obj"传递到函数中时,当我没有将"const Class &obj"传递给构造函数时,复制构造函数如何工作。 我有这个疑问,因为关于I C ++的书正在阅读,刚刚提到了什么是复制构造器以及如何实现它。 但没有提到它是如何被调用的。 我是 C++ 的新手。 我用谷歌搜索了它,但找不到它是怎么回事被召唤。提前感谢你:)

class Line{
  public:
   int getLength( void );
   Line( int len );             // simple constructor
   Line( const Line &obj);  // copy constructor
  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
}
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;
}

复制构造函数是一个特殊函数。在某些情况下,编译器会自动调用它。其中一个条件是,当函数中具有非引用参数,并将 L 值对象作为参数传递给该函数时。参数使用复制构造函数初始化,传递给函数的参数用作复制构造函数的参数。

编译器代表您执行各种操作,而无需显式执行这些操作。这是其中之一,它符合语言的规则。