C++使用声明

C++ using declaration

本文关键字:声明 C++      更新时间:2023-10-16

为什么下面的using ::foo声明隐藏了所有其他foo函数?

#include <iostream>
void foo(double) { std::cout << "::foo(double)" << std::endl; }
struct A {
  void foo(float) { std::cout << "A::foo(float)" << std::endl; }
  void foo(int) { std::cout << "A::foo(int)" << std::endl; }
  void foo() { std::cout << "A::foo()" << std::endl; }
};
struct B : A {
  using A::foo;
  void foo(int) { std::cout << "B::foo(int)" << std::endl; }
  void foo() { std::cout << "B::foo()" << std::endl; }
  void boo() {
    using ::foo;
    foo(1.0);
    foo(1.0f);
    foo(1);
    foo();
  };
};
int main() {
  B b;
  b.boo();
  return 0;
}

内部作用域中函数的任何声明都会隐藏外部作用域中同名函数的所有声明。

您在函数boo函数::foo 的块范围中声明

  void boo() {
    using ::foo;
    foo(1.0);
    foo(1.0f);
    foo(1);
    foo();
  };

它将所有具有相同名称的函数隐藏在封闭作用域中。

更确切地说。根据C++标准

13由于使用声明是一种声明,因此对同一声明性区域中的同名声明(3.3)也适用于使用声明

或者,最好引用C++标准中的以下引用

1 using声明将名称引入中的声明性区域出现using声明。using声明:成员名称在using声明中指定的是在声明性区域中声明的其中出现using声明。