“在外部作用域中定义的具有相同名称的实体被隐藏”不成立

问题描述 投票:0回答:1

在“ C ++ Primer”第五版中,第18.2.2节的第二页中有一行“隐藏了在外部作用域中定义的具有相同名称的实体”。这句话用红色强调,如下所示:

enter image description here

我试图在一个实验中重复这一主张。实验代码如下:

#include <cstdlib>
#include <iostream>
#include <cmath>

int abs(int n) {
    std::cout << "here" << std::endl;
    return 0; 
}

void test() {
    using std::abs;
    std::cout << abs(7) << std::endl;    
}

int main(int argc, char** argv) {
    test();

    return 0;
}

using std::abs是使用声明,因此,如果“ C ++ Primer”中的声明正确,则用户定义的abs()函数应由std::abs()隐藏。但是结果是调用的是用户定义的abs()函数。因此,如果这本书是正确的,则我的实验肯定有问题。如何编写实验代码以确认“ C ++ Primer”中的句子?如果书不正确,那可以代替句子的正确解释是什么?谢谢。

PS:我在Windows10 + VS2015和Ubuntu 18.04 + g ++ 7.4中都尝试过。两者都称为用户定义的abs(),并在“此处”打印输出。

c++ scope namespaces using using-declaration
1个回答
0
投票

这本书可以更好地解释它,但这没错。只是对于重载的查找规则有些微妙,因为同名的重载通常可以在同一范围内共存,因此using声明与之混在一起。

例如,如果您确实要定义一个非重载的新实体,则>]

void test() {
    int abs = 0;
    std::cout << abs(7) << std::endl;    
}

然后,该调用表达式将格式错误,因为外部可调用实体被内部int变量隐藏。解决该问题的方法是使用using声明

void test() {
    int abs = 0;
    {
      using std::abs; // Let the name refer to the functions again
      using ::abs;    // the variable abs is hidden
      std::cout << abs(7) << std::endl;    
    }
}

此实验应说明这本书的含义。

© www.soinside.com 2019 - 2024. All rights reserved.