c++ - "Entities with the same name defined in an outer scope are hidden"不成立

标签 c++ scope namespaces using using-declaration

在《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是 using 声明,因此,如果“C++ Primer”中的声明正确,则用户定义 abs()函数应该被 std::abs() 隐藏.但是结果是用户自定义的abs()被调用的函数。所以,如果这本书是正确的,那么我的实验肯定有问题。如何编写实验代码来确认“C++ Primer”中的句子?如果这本书不正确,可以代替句子的正确论述应该是什么?谢谢你。

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

最佳答案

这本书可以更好地解释它,但这并没有错。只是重载的查找规则有些微妙,因为同名的重载通常可能共存于同一范围内,因此 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;    
    }
}

这个实验应该说明这本书的意思。

关于c++ - "Entities with the same name defined in an outer scope are hidden"不成立,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60134540/

相关文章:

c# - .net:为什么在命名空间中使用 int 是不合法的?

c++ - remove() 函数删除所有其他文件

c++ - 在 MS-DOS 中使用长参数列表(超过 128 个字符)进行编译

c++ - 使用指针 C++ 时的错误消息

C++11 迭代器和返回的 std::unique_ptr 的范围

R - 未导出的函数仍然暴露给用户

c++ - 实现结构化张量

javascript - 一个 "safe place"来评估 Javascript 中的受信任代码(具有特定上下文)? [编辑: how can you break it?]

javascript - 揭示模块模式和范围

clojure - 获取可用的 clojure 命名空间