在私有成员函数中非法引用非静态成员

Illegal Reference to Non-static Member in Private Member Function

本文关键字:非法 引用 静态成员 函数 成员      更新时间:2023-10-16

我想写一个程序,但我不知道为什么我的私人成员函数不能访问我的私人数据成员。有人来帮忙吗?这是我的函数。nStocks、capacity和slots[]都是私有数据成员,hashStr()是私有函数。

bool search(char * symbol)
{
    if (nStocks == 0)
            return false;
    int          chain = 1;
    bool         found = false;
    unsigned int index = hashStr(symbol) % capacity;
    if (strcmp(symbol, slots[index].slotStock.symbol) != 0)
    {
            int start = index;
            index ++;
            index = index % capacity;
            while (!found && start != index)
            {
                    if(symbol == slots[index].slotStock.symbol)
                    {
                           found = true;
                    }
                    else
                    {
                            index = index % capacity;
                            index++;
                            chain++;
                    }
            }
            if (start == index)
                    return false;
    }
    return true;
}

这是我的。h文件的私有成员部分:

private:
    static unsigned int hashStr(char const * const symbol); // hashing function
    bool search(char * symbol);
    struct Slot
    {
            bool    occupied;
            Stock   slotStock;
    };
    Slot    *slots;                     // array of instances of slot
    int capacity;                   // number of slots in array
    int nStocks;                    // current number of stocks stored in hash table

如果我能提供更多的信息,请告诉我

代码创建了一个名为search的非成员函数。您需要更改:

bool search(char * symbol)

:

bool ClassName::search(char * symbol)

ClassName替换为类名

函数是静态的,这就是为什么。静态函数只能访问类的静态成员。

编辑:实际上你必须澄清你的问题,因为其他答案也可能是正确的…