代码之家  ›  专栏  ›  技术社区  ›  KeyC0de

C++嵌套类模板错误C2440'=:不能从“类型”转换为“相同类型”

  •  2
  • KeyC0de  · 技术社区  · 7 年前

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

    Error   C2440   'initializing': cannot convert from 'HashTable::HashTableEntry *' to 'HashTable::HashTableEntry *'`
    Error C2440 '=': cannot convert from 'HashTable::HashTableEntry *' to 'HashTable::HashTableEntry *'
    

    它发生在我的 HashTable 类, rehash() 功能。下面是代码段:

    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 的内存地址,然后 指向 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
    

    为什么会这样?我怎样才能做到这一点?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Remy Lebeau    7 年前

    为什么 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;
            ...
        }
        ...
    };
    
    推荐文章