深拷贝(可能与指针有关)
所以我想深拷贝我的HashTable。我的哈希表是一个填充链表的数组。 我已经编码链接列表构造函数/复制构造函数/重载操作符,他们完美地工作。深拷贝(可能与指针有关)
所以我编写了以下代码,但for循环中存在一个问题。
HashTable.cpp
HashTable::HashTable()
{
}
HashTable::HashTable(const HashTable & ht)
{
bucketSize = ht.bucketSize;
count = ht.count;
LinkedList** table = new LinkedList*[ht.bucketSize];
for (int i = 0; i < bucketSize; i++) {
table[i] = new LinkedList(ht.table[i]);
}
}
HashTable.h
class HashTable {
public:
HashTable();
HashTable(const HashTable& ht);
private:
// Add your member variables and any private member functions here
int bucketSize = defaultCapacity; //default is 101
int count = 0;
LinkedList table[defaultCapacity];
}
我怀疑它是与指针,但是没有错误信息,只有一个弹出当我按运行:中止()被调用。
在提供的源代码中,类和构造函数声明中都存在错误。为了更好地检测这些误解,最好在编译器解析它时呈现源代码。
第一步 - 在class HashTable
中,所有变量只声明且未初始化。
The
table
variable has to store an array ofLinkedList
. It is aLinkedList **table;
as declared in the copy-constructor.
class HashTable {
public:
HashTable(void);
HashTable(const HashTable& ht);
private:
// Add your member variables and any private member functions here
int bucketSize;
int count;
LinkedList **table;
};
第二步 - 默认构造函数HashTable(void);
将使用DefaultCapacity
参数。
In a default constructor
HashTable(void)
, adefaultCapacity
array is created and initialized with defaultLinkedList()
= Empty List.
HashTable::HashTable(void)
{
bucketSize = defaultCapacity; //default is 101
count = 0;
table = new LinkedList*[bucketSize];
for (int i = 0; i < bucketSize; i++) {
table[i] = new LinkedList();
}
}
第三步 - 拷贝构造函数HashTable(const HashTable & ht)
创建克隆阵列和重复项,LinkedList的。
In the copy constructor, each item is initialized with the
LinkedList
copy constructor.Error: the local declaration of
LinkedList** table
override the class declaration.
HashTable::HashTable(const HashTable & ht)
{
bucketSize = ht.bucketSize;
count = ht.count;
//LinkedList** table = new LinkedList*[ht.bucketSize];
table = new LinkedList*[ht.bucketSize];
for (int i = 0; i < bucketSize; i++) {
table[i] = new LinkedList(ht.table[i]);
}
}
请尝试创建一个[最小,完整,可验证的示例](http://*.com/help/mcve)向我们展示。 –
另外,你不认为这可能是一个问题,你有一个名为'table'的成员变量,并且在复制构造函数中具有相同名称的***局部变量***? –
如果我将该行更改为: table = new LinkedList [ht.bucketSize]; 我得到一个错误,说,表必须是一个可修改的左值。 虽然我不想改变它。我试图创建一个新的HashTable,而不是修改现有的。 – t3hdaniel