什么时候需要在C ++中的匿名类? [英] When do I need anonymous class in C++?
问题描述
在C ++中有一个称为匿名类的功能。它类似于C中的匿名结构。我认为这个特性是由于某些需求而发明的,但我不知道是什么。
There's a feature called anonymous class in C++. It's similar with anonymous struct in C. I think this feature is invented because of some needs, but I can't figure out what that is.
我可以有一些真正需要匿名类的例子吗?
Can I have some example which really needs anonymous class?
推荐答案
这个特性是因为 struct
和 class是同样的东西 - 你可以做的任何事情,你可以做与另一个。它的作用与C中的匿名
struct
完全相同;当你想将一些东西组合在一起并声明它的一个或多个实例,但不需要按名称引用该类型。
The feature is there because struct
and class
are the same thing - anything you can do with one, you can do with the other. It serves exactly the same purpose as an anonymous struct
in C; when you want to group some stuff together and declare one or more instances of it, but don't need to refer to that type by name.
C ++,部分是因为C ++设计倾向于更加面向类型,部分是因为你不能为匿名类声明构造函数或析构函数。
It's less commonly used in C++, partly because C++ designs tend to be more type-oriented, and partly because you can't declare constructors or destructors for anonymous classes.
这篇关于什么时候需要在C ++中的匿名类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!