了解'using'关键字:C ++ [英] Understanding 'using' keyword : C++

查看:165
本文介绍了了解'using'关键字:C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释下面的输出吗?

Can someone please explain below output:

#include <iostream>

using namespace std;

namespace A{
    int x=1;
    int z=2;
    }

namespace B{
    int y=3;
    int z=4;
    }

void doSomethingWith(int i) throw()
{
    cout << i ;
    }

void sample() throw()
{
    using namespace A;
    using namespace B;
    doSomethingWith(x);
    doSomethingWith(y);
    doSomethingWith(z);

    }

int main ()
{
sample();
return 0;
}

输出:

$ g++ -Wall TestCPP.cpp -o TestCPP
TestCPP.cpp: In function `void sample()':
TestCPP.cpp:26: error: `z' undeclared (first use this function)
TestCPP.cpp:26: error: (Each undeclared identifier is reported only once for each function it appears in.)

推荐答案

using关键字用于

  1. 快捷方式名称,因此您无需键入std::cout

使用模板(c ++ 11),即template<typename T> using VT = std::vector<T>;

to typedef with templates(c++11), i.e. template<typename T> using VT = std::vector<T>;

根据您的情况,namespace用于防止名称污染,这意味着两个函数/变量意外共享相同的名称.如果将两个using一起使用,则会导致z含糊不清.我的g ++ 4.8.1报告了错误:

In your situation, namespace is used to prevent name pollution, which means two functions/variables accidently shared the same name. If you use the two using together, this will led to ambiguous z. My g++ 4.8.1 reported the error:

abc.cpp: In function ‘void sample()’:
abc.cpp:26:21: error: reference to ‘z’ is ambiguous
     doSomethingWith(z);
                     ^
abc.cpp:12:5: note: candidates are: int B::z
 int z=4;
     ^
abc.cpp:7:5: note:                 int A::z
 int z=2;
     ^

这是预期的.我不确定您使用的是哪个gnu编译器,但这是可预见的错误.

which is expected. I am unsure which gnu compiler you are using, but this is an predictable error.

这篇关于了解'using'关键字:C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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