小编Win*_*Ray的帖子

使用声明隐藏名称

#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
查看次数