让我们看下面的代码:
#include <string> // std::string
using namespace std;
int main() {
//const::int i = 42; -> Error: "expected id-expression before 'int'"
const::string str = "Foo"; // No error: why?
}
为什么这段代码可以编译?仅当 XXX 是基本类型时才会出现错误“expected id-expression before XXX”。
const::char c = 1; // error: expected id-expression before 'char'
const::double d = 2; // error: expected id-expression before 'double'
const::float f = 3; // error: expected id-expression before 'float'
const::bool b = 4; // error: expected id-expression before 'bool'
最佳答案
const::string
被解析为 const::string
。 ::string
表示在全局命名空间中查找string
,并且由于你已经将std
注入(inject)到全局命名空间中,所以std: :string
找到了,一切都很好。
int
是内置类型,不在任何命名空间中,因此不存在 ::int
或 std::int< 这样的东西
,因此错误。
关于c++ - 范围解析运算符和常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34630710/