【发布时间】:2018-12-28 06:02:26
【问题描述】:
我在下面的代码中得到 2 个(可能)相同的错误:
错误 C2440 '正在初始化':无法从 'HashTable::HashTableEntry *' 转换为 'HashTable::HashTableEntry *'` 错误 C2440 '=':无法从 'HashTable::HashTableEntry *' 转换为 'HashTable::HashTableEntry *'它出现在我的HashTable 类rehash() 函数中。这是下面的代码sn-p:
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
为什么会这样?我怎样才能做到这一点?
【问题讨论】:
标签: c++ visual-studio templates inner-classes