首页 > 文章列表 > C++ 函数名中使用哪些关键字是禁止的?

C++ 函数名中使用哪些关键字是禁止的?

关键字 c++
365 2024-10-02

函数名中禁止使用关键字 new 和 delete,因其为预定义运算符。例如,函数名 deleteList 会导致编译错误,可将其改为 removeList 等其他名称。

C++ 函数名中使用哪些关键字是禁止的?

C++ 函数名中禁止使用的关键字

在 C++ 中,函数名不能包含以下关键字:

  • new
  • delete

这是因为这些关键字是 C++ 中预定义的运算符,用于分配和释放内存。如果函数名包含这些关键字,编译器会将函数名解释为运算符,而不是函数。

实战案例

以下代码会产生编译错误,因为函数名 deleteList 包含禁止使用的关键字 delete

void deleteList(int* list) {
  // ...
}

int main() {
  int list[] = {1, 2, 3};
  deleteList(list); // 编译错误
  return 0;
}

要修复此错误,可以将函数名更改为其他名称,例如 removeList

void removeList(int* list) {
  // ...
}

int main() {
  int list[] = {1, 2, 3};
  removeList(list); // 编译通过
  return 0;
}