【问题标题】:C++ Nested class template Error C2440 '=': cannot convert from 'type' to 'same type'C++ 嵌套类模板错误 C2440“=”:无法从“类型”转换为“相同类型”
【发布时间】:2018-12-28 06:02:26
【问题描述】:

我在下面的代码中得到 2 个(可能)相同的错误:

错误 C2440 '正在初始化':无法从 'HashTable::HashTableEntry *' 转换为 'HashTable::HashTableEntry *'` 错误 C2440 '=':无法从 'HashTable::HashTableEntry *' 转换为 'HashTable::HashTableEntry *'

它出现在我的HashTablerehash() 函数中。这是下面的代码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&lt;&gt;他们 - 不好。然后我取出了嵌套类 - 仍然是同样的错误。最后我尝试了reinterpret_cast&lt;&gt; 并且第一个错误(初始化)消失了,但是第二个错误奇怪地仍然存在:

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


    【解决方案1】:

    为什么HashTableEntryrehash() 使用自己的参数进行模板化,这些参数反映了HashTable 的模板参数?您应该从HashTableEntryrehash() 中删除模板,并让它们从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;
            ...
        }
        ...
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-15
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 2020-04-24
      相关资源
      最近更新 更多