hashnode构造函数如何初始化

How the hashnode constructor gets Initialized

本文关键字:初始化 构造函数 hashnode      更新时间:2023-10-16

我正在尝试使用单独的链接来实现哈希。虽然我们只是为类hashmap构造对象,但我无法理解hashnode构造函数是如何初始化的。它们彼此都是私有的,而且我还没有从hashnode派生类hashmap。那么这是怎么回事呢?

#include <iostream>
using namespace std;
static const int table_size = 10;
class hashnode {
        public:
            int key;
            int value;
            hashnode* next;
            hashnode(int key, int value)
            {
                this->key = key;
                this->value = value;
                this->next = NULL;
            }
};
class hashmap {
    hashnode** table;
public:
    hashmap()
    {
        table = new hashnode* [table_size];
        for(int i=0;i<table_size;i++)
        {
            table[i] = NULL; 
        }
    }
    int hash(int key)
    {
        return key%table_size;
    }
    void insert(int key, int value)
    {
        int hash_val = hash(key);
        hashnode* prev = NULL;
        hashnode* entry = table[hash_val];
        while(entry != NULL)
        {
            prev = entry;
            entry = entry->next;
        }
        if(entry == NULL)
        {
            entry = new hashnode(key,value);
            if(prev == NULL)
            {
                table[hash_val] = entry;
            }
            else
            {
                prev->next = entry;
            }
        }
        else
        {
            entry->value = value;
        }
    }
    void printtable(int key)
    {
         while(table[0] != NULL)
         {
            cout<<table[0]->key<<endl;
            table[0] = table[0]->next;
         }
    }  
};
int main()
{
hashmap hash1;
int key,value;
int choice;

table = new hashnode* [table_size];正在调用hashnode的构造函数。new就是这么做的;它为每个对象分配空间,然后调用对象的构造函数。

您要求编译器创建10个(基于table_sizehashnode对象。