无法访问模板

时间:2016-12-14 23:00:15

标签: c++ templates struct

我决定让我的HashTable类成为模板,这样我就可以练习制作模板,但是我遇到了问题。在我的HashTable<T>模板中,我有一个名为items Bucket的数据成员数组,它是HashTable<T>类中的结构。初始化items后,我无法访问模板代码中其他位置的Bucket成员。

我尝试在结构和变量定义之前放置typenametemplate<class T>,但无法使其正常工作。

以下是一段代码,它给出了错误'keyValue': undeclared identifier

#ifndef HASH_TABLE_
#define HASH_TABLE_

using namespace std;
#include <iostream>

template<class T>
class HashTable
{

public:

HashTable(int numItems) {
    if (numItems <= 0) {
        throw std::invalid_argument("Invalid HashTable size");
    }
    currItems = 0;

    //B must be the next prime after 2 * numItems
    B = 1000;

    items = Bucket[B]; //allocate array of Buckets

    items[0].keyVal; //ERROR: undeclared identifier
}

bool insert(T* newItem, int key) {
    bool retVal = false;

    if (currItems < B && newItem != NULL) { //cannot insert to full HashTable
        int index = 0;

        items[index].dataPtr = newItem; //ERROR:undeclared
        items[index].keyVal = key;      //ERROR:undeclared

        retVal = true;
        currItems++;
    }

    return retVal;
}

private:

struct Bucket {
    T* dataPtr = NULL;
    int keyVal = -1;
};

Bucket * items; //array of buckets
int B; //size of itemArray
int currItems; //track number of items in HashTable

};

#endif

为什么items[x]无法访问Bucket,因此无法使用items[x].keyValitems[x].dataPtr?我尝试了不同类型的初始化,例如items = new Bucket[B],但这也没有用,所以我假设我的错误存在于模板方面。

我感谢任何指导!

1 个答案:

答案 0 :(得分:0)

在使用之前,您必须声明>>> [new_dict(d) for d in students] [{'child_height': '20cm', 'student_name': 'Jack', 'student_status': 'Average', 'student_subjects': {'student_subject1': 'English', 'student_subject2': 'Math'}}, {'child_height': '30cm', 'student_name': 'Tom', 'student_status': 'Good', 'student_subjects': {'student_subject1': 'English', 'student_subject2': 'Science'}}]

Bucket

PS。不要这样做:template<class T> class HashTable { struct Bucket { T* dataPtr = NULL; int keyVal = -1; }; public: HashTable(int numItems) { if (numItems <= 0) { throw std::invalid_argument("Invalid HashTable size"); } currItems = 0; //B must be the next prime after 2 * numItems B = nextPrime(numItems * 2); items = new Bucket[B]; // <-- you forgot the 'new' items[0].keyVal; //ERROR: undeclared identifier } bool insert(T* newItem, int key) { bool retVal = false; if (currItems < B && newItem != NULL) { //cannot insert to full HashTable int index = getOpenBucket(key); items[index].dataPtr = newItem; //ERROR:undeclared items[index].keyVal = key; //ERROR:undeclared retVal = true; currItems++; } return retVal; } private: Bucket * items; //array of buckets int B; //size of itemArray int currItems; //track number of items in HashTable }; 在头文件中 - 永远。

它是邪恶的和反社会的,因为它会毒化包含标题的每个cpp文件的全局命名空间。这是确保没有人使用你的图书馆的有保证的方法。