一个带有智能数组对象的类
A class with smart array objects
所以我有以下类:
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
,如果您添加这些的话。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 如何使用智能指针在二维上声明数组?
- 无法循环访问存储在智能指针中的数组
- 如何将元素添加到由智能指针控制的数组中
- 提升是否具有用于数组向量的智能指针
- 在Visual Studio调试器中查看C 智能指针数组的内容
- 指向智能指针托管数组中的智能指针
- 智能感知:数组可能没有这种类型的元素
- 指向数组子集的智能指针(c++11)
- 智能指针数组
- 如何检索智能指针数组的大小?(例如std::unique_ptr<int[]>)
- 如何创建智能指针数组
- 一个带有智能数组对象的类
- 如何使用智能指针包装数组
- 确定strftime字符数组最大大小的智能方法是什么?
- 智能指针数组删除器