c++ 复制构造函数_用C ++复制构造函数

复制构造函数是C++中用于创建类对象副本的特殊构造函数。它分为浅拷贝和深拷贝两种。浅拷贝会创建对象的按位副本,两个对象指向同一内存,而深拷贝则为动态分配的内存创建独立副本,确保对象间互不影响。C++编译器提供默认的浅拷贝构造函数,但处理动态内存时需要用户自定义深拷贝构造函数。
摘要由CSDN通过智能技术生成

c++ 复制构造函数

Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the classes.

复制构造函数是一种构造函数,用于创建类类型的现有对象的副本。 它通常采用X(X&)的形式,其中X是类名。 编译器为所有类提供默认的Copy构造函数。

复制构造函数的语法 (Syntax of Copy Constructor)

Classname(const classname & objectname)
{
    . . . .
}

As it is used to create an object, hence it is called a constructor. And, it creates a new object, which is exact copy of the existing copy, hence it is called copy constructor.

由于它用于创建对象,因此称为构造函数。 并且,它创建一个新对象,该对象是现有副本的精确副本,因此被称为副本构造函数

copy construction of objects

Below is a sample program on Copy Constructor:

下面是复制构造器上的示例程序:

#include<iostream>
using namespace std;
class Samplecopyconstructor
{
    private:
    int x, y;   //data members
    
    public:
    Samplecopyconstructor(int x1, int y1)
    {
        x = x1;
        y = y1;
    }
    
    /* Copy constructor */
    Samplecopyconstructor (const Samplecopyconstructor &sam)
    {
        x = sam.x;
        y = sam.y;
    }
    
    void display()
    {
        cout<<x<<" "<<y<<endl;
    }
};
/* main function */
int main()
{
    Samplecopyconstructor obj1(10, 15);     // Normal constructor
    Samplecopyconstructor obj2 = obj1;      // Copy constructor
    cout<<"Normal constructor : ";
    obj1.display();
    cout<<"Copy constructor : ";
    obj2.display();
    return 0;
}

Normal constructor : 10 15 Copy constructor : 10 15

普通构造函数:10 15复制构造函数:10 15

浅拷贝构造函数 (Shallow Copy Constructor)

The concept of shallow copy constructor is explained through an example. Two students are entering their details in excel sheet simultaneously from two different machines shared over a network. Changes made by both of them will be reflected in the excel sheet. Because same excel sheet is opened in both locations. This is what happens in shallow copy constructor. Both objects will point to same memory location.

通过示例说明了浅表复制构造函数的概念。 两名学生正在通过网络共享的两台不同计算机同时在excel表中输入他们的详细信息。 他们两个所做的更改将反映在excel工作表中。 因为在两个位置都打开了相同的Excel工作表。 这是浅拷贝构造函数中发生的事情。 两个对象将指向相同的内存位置。

Shallow copy copies references to original objects. The compiler provides a default copy constructor. Default copy constructor provides a shallow copy as shown in below example. It is a bit-wise copy of an object.

浅拷贝将对原始对象的引用复制。 编译器提供默认的副本构造函数。 默认副本构造函数提供一个浅表副本,如下例所示。 它是对象的按位复制。

Shallow copy constructor is used when class is not dealing with any dynamically allocated memory.

当类不处理任何动态分配的内存时,使用浅拷贝构造函数。

Shallow Copy Constructor

In the below example you can see both objects, c1 and c2, points to same memory location. When c1.concatenate() function is called, it affects c2 also. So both c1.display() and c2.display() will give same output.

在下面的示例中,您可以看到对象c1和c2都指向相同的内存位置。 c1.concatenate()函数时,它也会影响c2。 因此, c1.display()c2.display()都将提供相同的输出。

#include<iostream>
#include<cstring>
using namespace std;
class CopyConstructor
{
    char *s_copy;
    public:
    CopyConstructor(const char *str)
    {
        s_copy = new char[16]; //Dynamic memory allocation
        strcpy(s_copy, str);
    }
    /* concatenate method */
    void concatenate(const char *str)
    {
        strcat(s_copy, str); //Concatenating two strings
    }
    /* copy constructor */
    ~CopyConstructor ()
    { 
        delete [] s_copy;
    }
    void display()
    {
        cout<<s_copy<<endl;
    }
};
/* main function */
int main()
{
    CopyConstructor c1("Copy");
    CopyConstructor c2 = c1; //Copy constructor
    c1.display();
    c2.display();
    c1.concatenate("Constructor");    //c1 is invoking concatenate()
    c1.display();
    c2.display();
    return 0;
}

Copy Copy CopyConstructor CopyConstructor

复制复制CopyConstructor CopyConstructor

深度复制构造函数 (Deep Copy Constructor)

Let's consider an example for explaining deep copy constructor. You are supposed to submit an assignment tomorrow and you are running short of time, so you copied it from your friend. Now you and your friend have same assignment content, but separate copies. Therefore any modifications made in your copy of assignment will not be reflected in your friend's copy. This is what happens in deep copy constructor.

让我们考虑一个解释深度复制构造函数的示例。 您应该明天提交作业,而您的作业时间很短,所以您从朋友那里复制了作业。 现在,您和您的朋友拥有相同的任务内容,但是副本却不同。 因此,您对作业副本所做的任何修改都不会反映在您朋友的副本中。 这就是深度复制构造函数中发生的情况。

Deep copy allocates separate memory for copied information. So the source and copy are different. Any changes made in one memory location will not affect copy in the other location. When we allocate dynamic memory using pointers we need user defined copy constructor. Both objects will point to different memory locations.

深层复制为复制的信息分配单独的内存。 因此,源和副本是不同的。 在一个内存位置进行的任何更改都不会影响在另一个位置的复制。 当我们使用指针分配动态内存时,我们需要用户定义的副本构造函数。 这两个对象将指向不同的存储位置。

Deep Copy Constructor

General requirements for deep copy:

深层复制的一般要求:

  • A normal constructor.

    普通的构造函数。

  • A destructor to delete the dynamically allocated memory.

    一个析构函数,用于删除动态分配的内存。

  • A copy constructor to make a copy of the dynamically allocated memory.

    复制构造函数,用于复制动态分配的内存。

  • An overloaded assignment operator.

    重载的赋值运算符。

In the previous example you can see when c1 called concatenate(), changes happens in both c1 and c2, because both are pointing to same memory location.

在前面的示例中,您可以看到c1调用concatenate()时,c1和c2都发生了更改,因为两者都指向相同的内存位置。

In the below example you can see user defined copy constructor i.e deep copy constructor. Here both c1 and c2 points to different memory location. So changes made in one location will not affect the other.

在下面的示例中,您可以看到用户定义的副本构造函数,即深度副本构造函数。 这里c1和c2都指向不同的存储位置。 因此,在一个位置进行的更改不会影响另一位置。

#include<iostream>
#include<cstring>
using namespace std;
class CopyConstructor
{
    char *s_copy;
    public:
    CopyConstructor (const char *str)
    {
        s_copy = new char[16];  //Dynamic memory alocation
        strcpy(s_copy, str);
    }
    
    CopyConstructor (const CopyConstructor &str)
    {
        s_copy = new char[16]; //Dynamic memory alocation
        strcpy(s_copy, str.s_copy);
    }
    
    void concatenate(const char *str)
    {
        strcat(s_copy, str); //Concatenating two strings
    }

    ~CopyConstructor()
    { 
        delete [] s_copy;
    }

    void display()
    {
        cout<<s_copy<<endl;
    }
};
/* main function */
int main()
{
    CopyConstructor c1("Copy");
    CopyConstructor c2 = c1;    //copy constructor
    c1.display();
    c2.display();
    c1.concatenate("Constructor");    //c1 is invoking concatenate()
    c1.display();
    c2.display();
    return 0;
}

Copy Copy CopyConstructor Copy

复制复制复制复制构造函数复制

翻译自: https://www.studytonight.com/cpp/copy-constructor-in-cpp.php

c++ 复制构造函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值