如何创建指向数组类成员的指针?

How do I create a pointer to an array class member?

本文关键字:数组 成员 指针 何创建 创建      更新时间:2023-10-16

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

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

基本上,我只想返回一个指向@element的指针。所以我尝试创建一个指向@elementwordElement指针,并尝试返回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;
}
QuadraticHashTable<char*> table(100);
table.insert("HELLO WORLD");

HashedObject就是char*

您将"HELLO WORLD"传递给insert,这需要const HashedObject&

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

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

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