Import nested classes into namespace - C++(将嵌套类导入命名空间 - C++)
问题描述
假设我有这样的课程:
class A {
public:
class B {
// ...
};
static void f();
// ...
};
我可以将 B
称为 A::B
并将 f()
称为 A::f()
,但我可以将 B
和 f()
导入全局/当前命名空间吗?我试过了
I can refer to B
as A::B
and to f()
as A::f()
, but can I import B
and f()
into the global/current namespace? I tried
using A::B;
但这给了我一个编译错误.
but that gave me a compilation error.
推荐答案
你应该能够为类使用命名空间别名:
You should be able to use namespace aliases for the class:
using B = A::B;
但是你不能用成员函数做到这一点,甚至不能用静态成员函数.
However you can't do that with the member function, not even with static member functions.
根据this SO answer(What is the difference between 'typedef' and 'using'在 C++11) 这个 应该 是有效的,并且实际上以与 typedef
相同的方式创建类型别名.但是,它只是 C++11.
According to this SO answer (What is the difference between 'typedef' and 'using' in C++11) this should be valid, and actually creates a type alias in the same way that typedef
does. However, it's C++11 only.
在 C++11 中有一个静态成员函数的解决方法,通过声明一个指向静态函数的变量:
There is a workaround for static member functions in C++11, by declaring a variable pointing to the static function:
struct Foo
{
static void bar()
{ }
};
auto bar = Foo::bar;
当然,在旧的 C++ 标准中也可以有一个指向静态成员函数的全局变量,但它比使用 auto
更混乱C++11 的关键字.在上面的示例中,它将是:
Of course, having a global variable pointing to a static member function is possible in the older C++ standard as well, but it's more messy than using the auto
keyword of C++11. In the example above it would be:
void (*bar)() = Foo::bar;
这篇关于将嵌套类导入命名空间 - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将嵌套类导入命名空间 - C++
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01