gpt4 book ai didi

c++ - 与来自 time.h 的标识符 'clock' 发生冲突

转载 作者:行者123 更新时间:2023-11-30 02:29:12 26 4
gpt4 key购买 nike

下面的程序

#include <ctime>

struct clock {};

int main() {
clock c;
}

无法在 g++ 5.4 和 clang 3.8(Ubuntu 64 位)上编译。

g++输出

clock.cpp: In function ‘int main()’:
clock.cpp:6:11: error: expected ‘;’ before ‘c’
clock c;
^

clang 输出

clock.cpp:6:5: error: must use 'struct' tag to refer to type 'clock' in this scope
clock c;
^
struct
/usr/include/time.h:189:16: note: struct 'clock' is hidden by a non-type declaration of 'clock' here
extern clock_t clock (void) __THROW;
^
1 error generated.

诊断的形式略有不同,但都与同一问题相关。与标准 C 函数存在冲突 clock以及程序中定义的同名结构。相关声明来自time.h :

extern clock_t clock (void) __THROW;

问题是:这些符号不应该在 std 中吗?命名空间,因为程序包括 <ctime> ?有趣的是,这个声明位于一个宏之后的几行,该宏显示为 __BEGIN_NAMESPACE_STD。 .此外,在 <ctime> , 可以看到:

namespace std
{
using ::clock_t;
using ::time_t;
using ::tm;

using ::clock;
...
}

这里有什么错误吗?

谢谢。

最佳答案

The question is: shouldn't such symbols be in the std namespace...

是的,他们是。不幸的是,C++ 标准还允许实现将来自 C 库派生头文件的名称放入全局命名空间。在这种情况下,您会得到 std::clock ::clock .

这适用于所有 <c*>具有相应 <*.h> 的 C++ header C 版本。

关于c++ - 与来自 time.h 的标识符 'clock' 发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39852545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com