c++ - 范围解析运算符和常量

标签 c++

让我们看下面的代码:

#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 是内置类型,不在任何命名空间中,因此不存在 ::intstd::int< 这样的东西,因此错误。

关于c++ - 范围解析运算符和常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34630710/

相关文章:

c++ - 如何将具有无参数构造函数的对象放置到 std::map 中?

c++ - 头文件中的静态变量

c++ - 使用 google breakpad 注册异常处理程序时出现总线错误

c++返回类型具有当前类类型的指针

c++ - 使用c++修改的未关闭的文本文件安全吗?

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 如何通知最大长度溢出

c++ - 为什么 Win32 OleGetClipboard() 函数会返回 CLIPBRD_E_CANT_OPEN?

c++ - 为什么打印16而不是17并且变量不增加?

c++ - 将模板定义为变量的宏