gpt4 book ai didi

c++ - c++11 中的命名空间问题?

转载 作者:可可西里 更新时间:2023-11-01 17:46:10 26 4
gpt4 key购买 nike

谁能解释一下:

$ cat test.cpp 
#include <string>
std::string div;
$ g++ -c test.cpp
$ g++ -std=c++11 -c test.cpp
test.cpp:2:13: error: 'std::string div' redeclared as different kind of symbol
In file included from /usr/include/c++/4.7.1/cstdlib:66:0,
from /usr/include/c++/4.7.1/ext/string_conversions.h:37,
from /usr/include/c++/4.7.1/bits/basic_string.h:2814,
from /usr/include/c++/4.7.1/string:54,
from test.cpp:1:
/usr/include/stdlib.h:787:14: error: previous declaration of 'div_t div(int, int)'
$

对于 C++11 模式,div 符号不应该在 std 命名空间中吗?或者它是我的系统特有的东西?

最佳答案

/usr/include/stdlib.h

.h 中的每个名字C stdlib header 位于全局命名空间中(很明显)。

此外,任何cHEADER C++ stdlib header 将定义来自 HEADER.h 的相应名称在std命名空间,但也允许将它们放在全局命名空间中(这样他们就可以做

// cHEADER
#include <HEADER.h>

namespace std{
using ::one_name_from_HEADER;
using ::another_name_from_HEADER;
// and so on...
}

并完成它)。

§D.5 [depr.c.headers]

p2 Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).

p3 [ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std. —end example ]

如您所见,反之亦然(<HEADER.h> 可能会将名称引入 std 命名空间,就好像

// HEADER.h
#include <cHEADER>

using std::one_name_from_HEADER;
using std::another_name_from_HEADER;
// and so on...
}

),这使得这些 header 之间的整体区别相当……毫无用处,真的。

关于c++ - c++11 中的命名空间问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13040139/

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