【问题标题】:How do I create a pointer to an array class member?如何创建指向数组类成员的指针?
【发布时间】:2017-02-26 08:06:14
【问题描述】:

我正在尝试使用 find 函数从我的哈希表中返回数组 @element 的地址。但是,我收到编译器错误:

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

基本上,我只想返回一个指向@element 的指针。所以我尝试创建一个指向@element 的指针wordElement 并尝试返回wordElement。但这没有用。这是我的代码的 sn-p,我不知道如何在 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;
    }

【问题讨论】:

  • 我们不知道 ITEM_NOT_FOUND 是什么,但无论如何设计都不可行。 array[currentPos].element 是一个 char 数组。该函数尝试返回HashedObj &amp;。这行不通。你为什么要设计一个特殊的“非价值”价值?你知道the billion dollar mistake是什么吗?

标签: c++ arrays pointers


【解决方案1】:
QuadraticHashTable<char*> table(100);
table.insert("HELLO WORLD");

HashedObject 是 char*

您将"HELLO WORLD" 传递给insert,它需要const HashedObject&amp;。

那里的const 适用于顶层,因此它是char* const&amp; 而不是const char*&amp;(这将是一个不同的错误)。

鉴于您的条目基本上是 char[20] 以及您编写条目的方式,此代码仅在 HashedObjects 是原始 C 字符串时才有效。模板参数在编写时毫无意义。就是这样。

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

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多