2017-02-26 87 views
0

我想使用find函数从我的哈希表中返回数组@element的地址。不过,我收到编译器错误:如何创建一个指向数组类成员的指针?

QuadraticProbing.cpp:134:59: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive] 
      return isActive(currentPos) ? wordElement : ITEM_NOT_FOUND; 

基本上,我只是想返回一个指向@element。所以我试着创建一个指针wordElement@element并试着返回wordElement。但那并不奏效。这里是我的代码片段,我无法弄清楚如何在HashEntry中获得指向@element的指针。

//Main 
int main() 
{ 
    QuadraticHashTable<char*> table(100); 
    table.insert("HELLO WORLD"); 
    if (table.find(document[i]) == NULL)) 
     cout << "OH NO!"; 
} 

//Class that has element that I want to return in find. 
template <class HashedObj> 
class QuadraticHashTable 
{ 
    public: 
    QuadraticHashTable() 

    const HashedObj & find(const HashedObj & x) const; 

    enum EntryType { ACTIVE, EMPTY, DELETED }; 
    private: 
    struct HashEntry 
    { 
     char element[20]; 
     EntryType info; 


     HashEntry(const HashedObj & e = HashedObj(), EntryType i = EMPTY) 
      : info(i) 
      { 
      if (e != NULL) 
       strcpy(element, e); 
      } 
    }; 
     vector<HashEntry> array; 

//Find Function 
    template <class HashedObj> 
    const HashedObj & QuadraticHashTable<HashedObj>::find(const HashedObj & x) const 
    { 
     int currentPos = findPos(x); 
     const char * wordElement = array[currentPos].element; 
     return isActive(currentPos) ? wordElement : ITEM_NOT_FOUND; 
    } 
+0

我们不知道ITEM_NOT_FOUND是什么,但无论如何设计都不可行。 'array [currentPos] .element'是一个'char'数组。该函数试图返回一个'HashedObj&'。这是行不通的。你为什么要设计一个特殊的“非价值”价值?你知道[十亿美元的错误](http://lambda-the-ultimate.org/node/3186)是什么吗? –

回答

2
QuadraticHashTable<char*> table(100); 
table.insert("HELLO WORLD"); 

一个HashedObjectchar*

您传递"HELLO WORLD"insert,这需要一个const HashedObject&

const那里适用于顶级,所以它是一个char* const&而不是const char*&(这将是一个不同的错误)。

考虑到您的输入基本上是char[20]以及您如何编写输入,此代码仅适用于HashedObject是原始C字符串。写入的模板参数毫无意义。所以就是这样。

但是char const*作为模板参数是使代码编译的另一种方法。但是,真的,一个只适用于一种类型的模板是毫无意义的。