什么是NULL,是否需要声明?

时间:2011-10-13 00:30:44

标签: c++

在这个片段中,我发现here有一个简单的C ++哈希,到处都是NULL我得到了

  

在此范围内未声明NULL。

我正在使用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;
      }
};

2 个答案:

答案 0 :(得分:5)

NULLstddef.h中声明的标准。您需要添加stddef.h(或cstddef)才能使用NULL

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

答案 1 :(得分:3)

正如其他地方所提到的NULLstddef.h中定义,也可能在其他一些系统头文件中定义(我最近没有检查过)。

如果您只使用C ++而不包含任何内容,那么您可以写:

#define NULL 0

位于文件的顶部,它将按预期工作。

在较新的C ++ 0x或C ++ 11中,编译器有一个关键字nullptr,而不是NULL0指针。