我在为哈希表编写复制构造函数时遇到了问题。我已经在单独使用链接对象的复制构造函数方面遇到了麻烦。如何使用以下函数实现复制构造函数和赋值运算符:
//copy constructor
Apple::Apple(const Apple& anotherApple){
}
//assignment operator
Apple& Apple::operator = (const Apple& anotherApple){
}
我知道它会是这样的:
tableSize = anotherApple.tableSize;
count = anotherApple.count;
array = new *anotherApple.array; //idk if this is right for dynamically created array of pointers
最佳答案
Apple::Apple(Apple const & anotherApple)
{
// allocate an array to hold pointers to Node
array = new Node*[tableSize];
for(int i=0; i<tableSize; i++)
{
Node* src = anotherApple.array[i];
Node* dest;
if (src == NULL)
{
array[i] = NULL;
continue; // no data to copy, continue to next row
}
// set array[i] since there is at-least one element
dest = new Node;
dest->data = src->data;
array[i] = dest;
src = src->next;
while(src != NULL)
{
Node* n = new Node;
dest->next = n;
dest = n;
dest->data = src->data;
src = src->next;
}
dest->next = NULL;
}
}
关于c++ - 哈希表的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487621/