BZ易风

导航

 

 

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

namespace LOL
{
    int swkId = 1;
}

void test01()
{
    int swkId = 2;

    using LOL::swkId;        //写了using声明后,下面这行代码说明以后看到的swkId是LOL命名空间下的
                            //但是编译器又有就近原则,就产生了二义性
    cout << swkId << endl;    //二义性报错
}
int main()
{
    test01();
    system("Pause");        //阻塞功能
    return EXIT_SUCCESS;    // 返回正常退出
}

结果:

避免二义性

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

namespace LOL
{
    int swkId = 1;
}

namespace King
{
    int swkId = 3;
}

void test01()
{
    int swkId = 2;
    using namespace LOL;        //写了using声明后,只是打开了命名空间 没有使用,不会产出二义性
                            
    cout << swkId << endl;        //就近原则 输出: 2
}
int main()
{
    test01();
    system("Pause");        //阻塞功能
    return EXIT_SUCCESS;    // 返回正常退出
}

使用多个命名空间下字段

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

namespace LOL
{
    int swkId = 1;
}

namespace King
{
    int swkId = 3;
}

void test01()
{
    using namespace LOL;        //写了using声明后,只是打开了命名空间 没有使用,不会产出二义性
    using namespace King;        //多个命名空间下相同字段名,产出二义性
    //cout << swkId << endl;        //报错
    cout << LOL::swkId << endl;        //使用指定命名空间下的变量
}
int main()
{
    test01();
    system("Pause");        //阻塞功能
    return EXIT_SUCCESS;    // 返回正常退出
}

 

posted on 2021-08-01 12:21  BZ易风  阅读(277)  评论(0编辑  收藏  举报