Latest web development tutorials

C ++ constructor de copia

Clase C ++ y objetos Clase C ++ y objetos

El constructor de copia es un constructor especial que cuando se crea un objeto, el objeto es utilizar el mismo tipo de creado previamente para inicializar el objeto recién creado.El constructor de copia se utiliza normalmente:

  • Mediante el uso de otro objeto del mismo tipo para inicializar el objeto recién creado.

  • Copia el objeto pasarlo como parámetro a la función.

  • Copiar el objeto, y el objeto es devuelto desde la función.

Si la clase no define un constructor de copia, el compilador en sí define una. Si la clase con una variable puntero, y la asignación dinámica de memoria, debe tener un constructor de copia. Copia constructor forma más común es la siguiente:

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

Aquí, obj es una referencia a un objeto, el objeto se utiliza para inicializar otro objeto.

#include <iostream>

using namespace std;

class Line
{
   public:
      int getLength( void );
      Line( int len );             // 简单的构造函数
      Line( const Line &obj);  // 拷贝构造函数
      ~Line();                     // 析构函数

   private:
      int *ptr;
};

// 成员函数定义,包括构造函数
Line::Line(int len)
{
    cout << "Normal constructor allocating ptr" << endl;
    // 为指针分配内存
    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;
}

// 程序的主函数
int main( )
{
   Line line(10);

   display(line);

   return 0;
}

Cuando el código se compila y ejecuta, produce los siguientes resultados:

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

Los siguientes ejemplos de el ejemplo anterior ligeramente modificada usando el mismo tipo de objetos tiene que inicializar el nuevo objeto creado:

#include <iostream>

using namespace std;

class Line
{
   public:
      int getLength( void );
      Line( int len );             // 简单的构造函数
      Line( const Line &obj);  // 拷贝构造函数
      ~Line();                     // 析构函数

   private:
      int *ptr;
};

// 成员函数定义,包括构造函数
Line::Line(int len)
{
    cout << "Normal constructor allocating ptr" << endl;
    // 为指针分配内存
    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;
}

// 程序的主函数
int main( )
{
   Line line1(10);

   Line line2 = line1; // 这里也调用了拷贝构造函数

   display(line1);
   display(line2);

   return 0;
}

Cuando el código se compila y ejecuta, produce los siguientes resultados:

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!

Clase C ++ y objetos Clase C ++ y objetos