所以我有以下类(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/