动态数组...复制构造函数,析构函数,重载赋值运算符 [英] Dynamic array... copy constructor, destructor, overloaded assignment operator

查看:370
本文介绍了动态数组...复制构造函数,析构函数,重载赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习中期考试。将有一个关于动态设置数组的问题,可能做一个复制构造函数,一个析构函数和重载赋值运算符。你能否证实我是否正确?另外我不明白什么是重载赋值运算符的意思。你能帮我一下吗?

I am studying for my midterm exam. There is going to be a question about setting up an array dynamically, and maybe doing a copy constructor, a destructor and overloading the assignment operator. Can you please verify if I am correct. Also I don't understand what overloading the assignment operator means. Can you help me out with this?

class A
{
int* myArray;   //basically I created a pointer called myArray, 
A()             //are my copy constructors correct? A(), and A(int size)?
{
    myArray = 0;
}
A(int size)
{
    myArray = new int[size];
}
~A()             // I think my destructor is correct
{
    delete [] myArray;
}

您能检查我的代码吗?

Can you check my code please? Also how do I overload assignment operator?

推荐答案

复制构造函数用于基于另一个相同类型的实例创建对象。你没有这样。您可以使用如下代码定义它:

The copy constructor is used for creation of object based on another's instance of the same type. You don't have such. You can define it using code like this:

A(const A &other)
{
   myArray = new int[other._size];
   _size = other._size;
   memcpy(myArray, other.myArray, sizeof(int) * _size);
}

您应该更改类,因此它将存储_size数组,需要将您的构造函数和析构函数的公开范围更改为public。

You should change your class, so it will store _size of array, you also need to change visibility of your constructors and destructor to public.

重载的赋值运算符应如下所示:

The overloaded assignment operator should look like this:

const A &operator=(const A &other)
{
   if(this == &other) return *this; // handling of self assignment, thanks for your advice, arul.
   delete[] myArray; // freeing previously used memory
   myArray = new int[other._size];
   _size = other._size;
   memcpy(myArray, other.myArray, sizeof(int) * _size);
   return *this;
}

您还可以在此赋值运算符中添加数组大小相等的检查,因此您将重用动态数组,而不必重新分配内存。

You also can add a check of equality of array sizes in this assignment operator, so you will reuse your dynamic array without unnecessary reallocations of memory.

这篇关于动态数组...复制构造函数,析构函数,重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆