C++使用声明
C++ using declaration
为什么下面的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声明。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别