相关疑难解决方法(0)

为什么"使用命名空间std"被认为是不好的做法?

我已经告诉别人,编写using namespace std;代码是错误的,我应该用std::coutstd::cin直接代替.

为什么被using namespace std;认为是不好的做法?是低效还是冒着声明模糊变量(与名称std空间中的函数具有相同名称的变量)的风险?它会影响性能吗?

c++ namespaces using-directives std c++-faq

2486
推荐指数
36
解决办法
78万
查看次数

使用声明隐藏名称

#include <iostream>

struct H
{
    void swap(H &rhs); 
};    

void swap(H &, H &)
{
    std::cout << "swap(H &t1, H &t2)" << std::endl;
}

void H::swap(H &rhs)
{
    using std::swap;
    swap(*this, rhs);
}


int main(void)
{
    H a;
    H b;

    a.swap(b);
}
Run Code Online (Sandbox Code Playgroud)

这就是结果:

swap(H &t1, H &t2)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我尝试定义一个交换函数H.在函数中void H::swap(H &rhs),我使用using声明使名称std :: swap可见.如果没有using声明,则无法编译代码,因为类中没有可用的带有两个参数的交换函数H.

我在这里有一个问题.在我看来,在我使用using声明之后 - using std::swap它只是使std :: swap - STL中的模板函数可见.所以我认为应该调用STL中的交换H::swap().但结果显示,void swap(H &t1, H &t2)而是调用了它.

所以这是我的问题:

  1. 为什么我不能在没有使用声明的情况下调用swap?(我想这是因为在类中没有带有两个参数的交换函数.但我不确定.)
  2. 为什么要调用我的定义的交换而不是调用STL交换H::swap

c++ swap using name-lookup argument-dependent-lookup

3
推荐指数
1
解决办法
143
查看次数