我在下面的代码中得到 2 个(可能)相同的错误:
Error C2440 'initializing': cannot convert from 'HashTable::HashTableEntry *' to 'HashTable::HashTableEntry *'` Error C2440 '=': cannot convert from 'HashTable::HashTableEntry *' to 'HashTable::HashTableEntry *'
It occurs in my HashTable
class, rehash()
function. Here's the code snippet below:
template<class T, class V>
class HashTable {
private:
template<class T, class V> struct HashTableEntry {
T key;
V value;
};
...
int size;
int capacity;
HashTableEntry<T,V>* A;
public:
// ctor
HashTable(int cap) :
size(0), capacity(cap), A(new HashTableEntry<T,V>[cap])
{
...
}
...
template<typename T, typename V> void rehash()
{
...
HashTableEntry<T,V>* newMemoryRegion = new HashTableEntry<T,V>[capacity];
HashTableEntry<T,V>* disposable = A; // FIRST ERROR HERE
A = newMemoryRegion; // SECOND ERROR HERE
...
}
...
}
我正在尝试做的(正如您可能意识到的那样)是获取 disposable
指向A
的内存地址,然后是 A
指向newMemoryRegion
的地址。
我试过 static_cast<>
他们——不好。然后我取出了嵌套类 - 仍然是同样的错误。最后我试了reinterpret_cast<>
第一个错误(初始化)消失了,但奇怪的是第二个错误仍然存在:
HashTableEntry<T,V>* disposable = reinterpret_cast<HashTableEntry<T, V>*>(A); // no more errors here
A = reinterpret_cast<HashTableEntry<T, V>*>(newMemoryRegion); // SAME SECOND ERROR persists here
为什么会这样?我怎样才能使它工作?
最佳答案
为什么 HashTableEntry
和 rehash()
使用它们自己的参数来模板化,这些参数反射(reflect)了 HashTable
的模板参数?您应该从 HashTableEntry
和 rehash()
中删除模板,让它们继承 HashTable
中的参数:
template<class T, class V>
class HashTable {
private:
struct HashTableEntry {
T key;
V value;
};
...
int size;
int capacity;
HashTableEntry* A;
public:
// ctor
HashTable(int cap) :
size(0), capacity(cap), A(new HashTableEntry[cap])
{
...
}
...
void rehash()
{
...
HashTableEntry* newMemoryRegion = new HashTableEntry[capacity];
HashTableEntry* disposable = A;
A = newMemoryRegion;
...
}
...
};
关于C++嵌套类模板错误C2440 '=' : cannot convert from 'type' to 'same type' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433831/