未命名的结构可以继承吗?

Nik*_*iou 29 c++ inheritance struct

以下看起来像编译错误:

struct : Base { };
Run Code Online (Sandbox Code Playgroud)

然而,当使用 [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;
}
Run Code Online (Sandbox Code Playgroud)

在c ++中它是否适用于未命名的结构继承?有没有这个用户的例子?


[1]免责声明:我不是假装提供的示例很有用.我很少使用未命名的结构,当我这样做时,它们通常将一些内置成员变量捆绑在一起,以便为类提供更清晰的接口.这个问题从观测上来memberspaces不需要nammed结构

das*_*ght 41

未命名的类可以继承.这很有用,例如,在必须继承以覆盖虚函数的情况下,但是您永远不需要多个类的实例,并且您不需要引用派生类型,因为对基数的引用类型就足够了.

这是一个例子:

#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;
}
Run Code Online (Sandbox Code Playgroud)

此代码创建四个匿名派生Base- 每个操作一个.当这些派生的实例传递给perform函数时,将调用正确的覆盖.注意,perform不需要知道任何特定类型 - 具有其虚函数的基类型足以完成该过程.

以下是运行上述代码的输出:

input: 2, 3; output: 5
input: 6, 1; output: 5
input: 6, 7; output: 42
input: 72, 8; output: 9
Run Code Online (Sandbox Code Playgroud)

在ideone上演示.


Ala*_*kes 9

你的第一个例子,因为它没有声明任何东西,显示了对匿名结构的尝试(不允许 - 7/3)而不是未命名的结构(这是).

C++ 11标准中9/1的语法似乎允许一个未命名的类具有基础,所以我认为你的第二个例子很好.