c++ - 什么是NULL,需要声明吗?

标签 c++

在这段代码中,我找到了 here对于到处都有 NULL 的简单 C++ 哈希,我得到一个

NULL was not declared in this scope.

我正在使用 MinGW 编译器 g++。我的猜测是 NULL 不是保留关键字?我如何确定 gcc 的版本并查看 C++ 关键字的引用列表?

此列表here声明 NULL 不是关键字。

int main()
  {
  }

const int TABLE_SIZE = 128;
class HashEntry 
  {
  private:
    int key;
    int value;
  public:
    HashEntry(int key, int value) 
      {
      this->key = key;
      this->value = value;
      }
    int getKey() 
      {
      return key;
      }
    int getValue() 
      {
      return value;
      }
  }; 
class HashMap 
  {
  private:
    HashEntry **table;
  public:
    HashMap() 
      {
      table = new HashEntry*[TABLE_SIZE];
      for (int i = 0; i < TABLE_SIZE; i++) table[i] = NULL;
      }
    int get(int key) 
      {
      int hash = (key % TABLE_SIZE);
      while (table[hash] != NULL && table[hash]->getKey() != key) hash = (hash + 1) % TABLE_SIZE;
      if (table[hash] == NULL)return -1;
      else return table[hash]->getValue();
      }
    void put(int key, int value) 
      {
      int hash = (key % TABLE_SIZE);
      while (table[hash] != NULL && table[hash]->getKey() != key)
      hash = (hash + 1) % TABLE_SIZE;
      if (table[hash] != NULL) delete table[hash];
      table[hash] = new HashEntry(key, value);
      }     
    ~HashMap() 
      {
      for (int i = 0; i < TABLE_SIZE; i++)
        if (table[i] != NULL) delete table[i];
      delete[] table;
      }
};

最佳答案

NULL 是在 stddef.h 中声明的标准。您需要包含 stddef.h(或 cstddef)才能使用 NULL

如果您不想包含任何内容,您始终可以使用 0 代替 NULL

关于c++ - 什么是NULL,需要声明吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7748133/

相关文章:

c++ - 使用复杂数据结构时内存泄漏( vector 数组的数组)

c++ - 试图理解 C++ 中的 * 和 &

c++ - 对于构造函数,我如何在可变参数模板与 std::initializer_list 之间进行选择?

c++ - 如何将蓝牙耳机与 Qt 库连接并管理输入/输出音频流

c# - 将 CRC 函数从 C++ 转换为 C#

c++ - Foo *foo; 之间的区别和噗噗;在 C++ 中

c++ - 在 C 中允许重复的 const 限定符但在 C++ 中不允许?

c++ - Knight's Tour C++ 使用堆栈

c++ - 链接错误 : <LNK1120> <LNK2020> Implement one serialization data class in C++

c++ - undefined reference