【问题标题】:C structure and C function with the same name in C++C++中同名的C结构体和C函数
【发布时间】:2021-08-05 12:40:24
【问题描述】:

当我混合 C 和 C++ 代码时,当 Linux C 结构 statxstatx() Linux 系统调用同名时遇到了问题。

对于statx()系统调用在安装的glibc版本中不存在的情况,我实现了我自己的statx()版本。我尝试在匿名命名空间中实现一个备用的statx() 函数,但在这种情况下代码无法编译。

我试图将示例代码简化到最低程度。

#include <iostream>

struct statx {};

namespace {

void statx() { std::cout << "Function statx()\n"; }

}

int main()
{
    statx();    // Compile error.
    ::statx();  // Calling constructor of struct instead of function statx().
}

用g++ 8编译的输出

g++ -std=c++17 -Wall -pedantic -Wextra str_fnc.cpp -o str_fnc


str_fnc.cpp: In function 'int main()':
str_fnc.cpp:13:5: error: reference to 'statx' is ambiguous
   13 |     statx();    // Compile error.
      |     ^~~~~
str_fnc.cpp:7:6: note: candidates are: 'void {anonymous}::statx()'
    7 | void statx() { std::cout << "Function statx()\n"; }
      |      ^~~~~
str_fnc.cpp:3:8: note:                 'struct statx'
    3 | struct statx {};
      |        ^~~~~
str_fnc.cpp: At global scope:
str_fnc.cpp:7:6: warning: 'void {anonymous}::statx()' defined but not used [-Wunused-function]
    7 | void statx() { std::cout << "Function statx()\n"; }
      |      ^~~~~

当我使用静态函数 statx() 而不是将其包含在匿名命名空间中时,代码编译并成功运行。

#include <iostream>

struct statx {};

static  // The replacement anonymous namespace with static function.
void statx() { std::cout << "Function statx()\n"; }

int main()
{
    statx();
    ::statx();
}

谁能解释为什么匿名命名空间中包含 statx() 的示例无法编译且不起作用?

【问题讨论】:

    标签: c++ static namespaces


    【解决方案1】:

    名称隐藏 [basic.scope.hiding]
    2. 如果一个类名([class.name])或枚举名([dcl.enum])和一个变量、数据成员、函数或枚举器在同一个声明区域(以任何顺序)以相同的名称声明(不包括通过 using 指令 ​​([basic.lookup.unqual]) 可见的声明),类或枚举名称在变量、数据成员、函数或枚举器名称可见的地方隐藏。

    所以在你的第二个例子中,这两个名称是在同一个声明区域中声明的,并且函数隐藏了结构名称。 (您仍然可以通过其详细类型说明符 struct statx 来引用该结构。

    在第一个示例中,函数是在不同的声明区域中引入的,因此该规定不适用。相反,正常的命名空间规则是有效的。即,内部名称就像使用声明一样被带到全局范围。如果您在未命名的命名空间内部和外部声明了相同的名称,则该名称在不合格时会变得不明确。您可以使用:: 选择外部名称,但无法从未命名的命名空间外部引用内部名称。

    【讨论】:

      猜你喜欢
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 2018-11-05
      • 2016-12-09
      • 2015-02-16
      • 2011-05-11
      相关资源
      最近更新 更多