c++ - 具有智能数组对象的类

标签 c++ arrays class

所以我有以下类(class):

class smartA
{
public:

int *p;
int size;

smartA(){size=10; p = new int [size];}
smartA (int x){size=x; p = new int [x];}
smartA(int y[], int x ){size=x; p = new int [x]; for (int i=0 ; i<x ; i++) p[i]=y[i];}
smartA(const smartA &a) {*this=a;}
~smartA(){delete [] p;}

void displayA()
{
for (int i=0; i<size; i++)
{   cout<<setw(4)<<p[i];
if (((i+1)%5)==0 && i!=0)
cout<<endl;}
    cout<<endl<<endl;
}

void setsmartA(const int a[], int sizea) 
{size=sizea; p = new int[size]; for (int i=0 ; i<size ; i++) p[i]=a[i];}

};

如何编写将两个智能数组对象合并为第三个智能数组对象的函数。 我无法访问每个智能数组的元素,因为它必须是动态数组。

例如,添加以下成员函数会给我一个错误:

smartA add(smartA a)
{
smartA c(a.size+size);

int i=0;
for ( ; i<a.size ;i++)
c.p[i]=a.p[i];

for (int j=0; j<a.size+size; j++, i++)
c.p[i]=p[j];

return c;}

最佳答案

How can I write a function that merges two smart array objects into a third smart array objects. [...] The adding following member function gives me an error.

除非在类定义中内联,否则 smartA add(smartA a) 应该是 smartA smartA::add(smartA const& a)。这是因为否则 add 将被视为类外的通用函数。请注意,将引用传递给 add 而不是拷贝是有意义的。

此外,在数组的上下文中,重载 operator+ 而不是调用 add 方法是有意义的。因此,您可能希望在以下位置实现 add:

friend smartA smartA::operator+(smartA const&, smartA const&);

最后,您的复制构造函数中有一个非常的问题:

smartA(const smartA &a) {*this=a;}

这会导致 aliasing并导致崩溃或内存问题。你想看看深拷贝The rule of Three .

关于c++ - 具有智能数组对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16173757/

相关文章:

php - 如何在 PHP 中对数组和数据进行排序?

javascript - 在哪里放置另一个 javascript 类中的(类)依赖项?

c++ - 用于随机访问和循环元素的最佳数据结构(C++)

arrays - 当我尝试将元素放入单元格时,为什么我的分割数组会抛出错误?

c++ - 使用模板编译错误 - 没有匹配的调用函数

javascript - 如何检查字符串是否在数组中?

ios - 将数据加载到类中并使用它的策略

python - Pylint 说 : W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

c++ - 给定均匀随机数生成器生成随机数

c++ - 使用宏进行赋值和错误检查