一个带有智能数组对象的类

A class with smart array objects

本文关键字:数组 智能 对象 一个      更新时间:2023-10-16

所以我有以下类:

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;}

如何编写一个函数,将两个智能数组对象合并为第三个智能数组对象。[…添加下面的成员函数给了我一个错误。

除非在类定义中内联,否则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;}

这会导致混叠并导致崩溃或内存问题。你要看一下深度拷贝三的规则

通过引用将参数传递给friend函数。按值返回

class smartA
{
  int *p;
  int size;
public:
....
  friend smartA operator+ (const SmartA& sa1, const SmartA& sa2);
};
smartA operator+ (const SmartA& sa1, const SmartA& sa2)
{
  SmartA res(sa1.size + sa2.size);
  for(int i = 0; i < sa1.size; i++)
    res.p[i] = sa1.p[i];
  for(int i = sa1.size, j = 0; i < sa1.size + sa2.size; i++, j++)
    res.p[i] = sa2.p[j];
  return res;
}
与您的代码片段不同,

我将成员设置为私有。最好从封装信息开始,并在需要时公开它,而不是反过来。

同样,您不需要将该函数设置为operator+或好友。我只是喜欢它的对称。

操作符可以灵活地将类型转换为smartA,如果您添加这些的话。