构造函数不更新类成员变量

Constructor doesn't update class member variables

本文关键字:成员 变量 更新 构造函数      更新时间:2023-10-16

所以我正在尝试实现一个哈希表,但我无法看到我的类或构造函数中出了什么问题。总之,当我尝试访问哈希表数组的元素时,我可以在构造函数中,但我不能在成员函数中(我得到 seg 错误(,这让我相信我的类/构造函数有问题不起作用。

website::website(int input) //Constructor
{       
    SIZE = input;
    node** hashtable = new node * [SIZE];
    for (int i = 0; i<SIZE; i++)
    {       
            hashtable[i] = NULL;
            if(!hashtable[i])
            {       
                    cout<<"It works at "<<i<<"th"<<endl;//This is to check
            }
    }
}
int website::hashfunction(const char  array []) //Hash function
{
    int inputsize = strlen(array);
    int value = 0;
    for (int i=0; i< inputsize; i++)
    {       
            value = value + int(array[i]);
    }
    value = value % SIZE;
    return value;
 }

这些函数执行它们应该执行的操作

但是当我运行这个函数时。我在hashtable[place]==NULL级别上遇到赛格错误。

int website::insert(const mainentry& input)
{
    int place = 0;
    node*temp = new node;
     /* Ignore this part
    temp->data.topic = new char[strlen(input.topic)+1];
    strcpy(temp->data.topic, input.topic);
    temp->data.url = new char[strlen(input.url)+1];
    strcpy(temp->data.url, input.url);
    temp->data.summary = new char[strlen(input.summary)+1];
    strcpy(temp->data.summary, input.summary);
    temp->data.review = new char[strlen(input.review)+1];
    strcpy(temp->data.review, input.review);
    temp->data.rating = input.rating;
    */
     place = hashfunction(temp->data.topic);
    cout<<"Place is: "<<place<<endl; //Hash function works correctly
    if (hashtable[place]== NULL) // THIS IS THE PART I GET SEG FAULT
    {
            hashtable[place] = temp;
            temp->next = NULL;
            return 1;
    }
    else
    {
            temp->next = hashtable[place];
            hashtable[place] = temp;
            return 1;
    }
return 0;
}

这是我的班级:

class website
{
        public:
                website(int input);
//              ~website();
                int insert(const mainentry & input);
                int retrieve( char [], mainentry output [] );
                int edit (mainentry & input);
                int remove();
                int display(char []);
                int display_all();
                int hashfunction(const char []);
        private:
                int SIZE;
                node ** hashtable;
};

假设我犯了一个初学者的错误,但我看不到发生了什么,如果有人可以指导我,我将不胜感激。

你通过编写以下内容在构造函数中隐藏类的hashtable变量:

website::website(int input) //Constructor
{       
    SIZE = input;
    node** hashtable = new node * [SIZE]; //<<-- Shadowing. you are declaring a local scope veriable called hastable, and not using the class's instance.
}

node** hashtable = new node * [SIZE];

应该是

hashtable = new node * [SIZE];