未命名的结构可以继承吗?
Can unnamed structures inherit?
下面的代码看起来像是编译错误:
struct : Base { };
然而,当使用[1]时,它似乎有效:
#include <iostream>
using namespace std;
template<bool B>
struct A
{
struct : std::integral_constant<bool, B> {
} members;
};
int main()
{
A<true> a;
cout << a.members.value << endl;
return 0;
}
在c++中,未命名的结构继承是有效的吗?有什么有用的例子吗?
[1] 免责声明:我不是假装提供的示例是有用的。我很少使用未命名的结构,当我这样做时,它们通常捆绑在一起一些内置的成员变量,以便为类提供一个更清晰的接口。这个问题来自于观察到成员空间不需要命名为结构
未命名的类可以继承。这很有用,例如,在必须继承才能覆盖虚函数的情况下,但永远不需要一个以上的类实例,也不需要引用派生类型,因为对基类型的引用就足够了。
下面是一个例子:
#include <iostream>
using namespace std;
struct Base {virtual int process(int a, int b) = 0;};
static struct : Base {
int process(int a, int b) { return a+b;}
} add;
static struct : Base {
int process(int a, int b) { return a-b;}
} subtract;
static struct : Base {
int process(int a, int b) { return a*b;}
} multiply;
static struct : Base {
int process(int a, int b) { return a/b;}
} divide;
void perform(Base& op, int a, int b) {
cout << "input: " << a << ", " << b << "; output: " << op.process(a, b) << endl;
}
int main() {
perform(add, 2, 3);
perform(subtract, 6, 1);
perform(multiply, 6, 7);
perform(divide, 72, 8);
return 0;
}
这段代码创建了Base
的四个匿名派生——每个操作一个。当这些派生的实例被传递给perform
函数时,将调用适当的覆盖。需要注意的是,perform
不需要知道任何具体的类型——基本类型和它的虚函数就足够完成这个过程了。
input: 2, 3; output: 5
input: 6, 1; output: 5
input: 6, 7; output: 42
input: 72, 8; output: 9
你的第一个例子,因为它没有声明任何东西,显示了一个匿名结构的尝试(这是不允许的- 7/3),而不是一个未命名的(这是)。
c++ 11标准的9/1中的语法似乎允许未命名的类有一个基,所以我认为你的第二个例子是好的。
相关文章:
- 为什么除了继承聚合结构之外,结构为空,无法聚合初始化?
- 将继承的结构传递给 poll()
- 继承层次结构并将元素添加到向量
- 具有菱形继承结构的子类的大小似乎很奇怪
- 如何向类添加继承结构,请参阅"enable_share_on_this"
- 在C 中继承C结构并将其传递回C库是安全的吗?
- 来自无法识别的继承结构的本地声明
- 继承结构的类型转换导致g++编译错误
- C++ 将结构函数作为继承结构中函数的参数传递
- 私下继承结构
- 有没有办法避免在特定自定义类继承结构中使用虚拟方法
- 可以在C++中类继承结构
- 当使用代码块13.12时,Doxygen没有产生正确的继承结构
- C++11 中的 POD 和继承.结构的地址 == 第一个成员的地址
- 具有带函数指针的类私有成员的继承结构
- 这种c++继承结构可能吗?
- 重写采用继承结构的函数
- 此继承结构是否存在切片问题
- 如何从基类继承结构成员
- 如何在c++中创建继承结构时设置父成员