关于名字查找

有人问我 CPP 在标识符前面加 :: 有什么用。直接上代码给回答:

#include <iostream>
using namespace std;
int a;
namespace tjua {
    int a;
    int *p=&::a; // :: 的用途
}

然后自己又想验证一下using在块作用域中的作用和全局是否一致,遂多打了几行:

namespace tjua{
    void f(int a);
}
void tjua::f(int a) {
    // using ::a; // error: target of using declaration conflicts with declaration already in scope
    // using namespace tjua; // neither error nor warning
    int *p1=&::a;
    int *p2=&tjua::a;
    int *p3=&a;
    cout << p1 << endl;
    cout << p2 << endl;
    cout << p3 << endl;
}

int main() {
    tjua::f(2); // output different Addr.
}

posted @ 2018-01-11 15:19  xxyyttxx  阅读(264)  评论(0编辑  收藏  举报