范围分辨率运算符和const [英] Scope resolution operator and const

查看:102
本文介绍了范围分辨率运算符和const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们来看下面的代码:

Let's take the following code:

#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?
}

为什么这段代码编译?

Why does this code compiles? The error "expected id-expression before XXX" is only present when XXX is a fundamental type.

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 ,并且由于您注入了

const::string is parsed as const ::string. ::string means to look up string in the global namespace, and since you have injected std into the global namespace, std::string is found and everything is dandy.

int 是一个内置类型,不在任何命名空间中,因此没有这样的事情 :: int std :: int ,因此出现错误。

int is a built-in type and isn't in any namespace, so there's no such thing as ::int or std::int, hence the error.

这篇关于范围分辨率运算符和const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆