请帮助我与c++命名空间

Please help me with C++ Namespace

本文关键字:c++ 命名空间 帮助      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
namespace A {
    int a = 10;
    void get_value(){ std::cout << "a = " << a << std::endl; }
}
namespace B {
    int b;
    void get_value(){ std::cout << "b =" << b << std::endl; }
}
void set_B();
int main(){
    using namespace A; 
    get_value(); 
    set_B();
    system("PAUSE");
    return 0;
}
void  set_B(){
    using namespace B;
    b = 15;
    get_value();    // Why call to get_value() is ambiguous, error is not generated here ?
 }

为什么在set_B()函数中调用get_value()没有歧义(A::get_value()B::get_value()),因为在set_B()中都显示为::get_value()

using namespace A;set_B中不活跃,因为它只出现在main中。它被限制在出现的范围内:main的正文

因为A::get_valueB::get_value通常在全局作用域中不可见。using namespace语句使得该命名空间中的声明在set_B中可见。