本文介绍了未命名的结构可以继承吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容看起来像是编译错误:

The following looks like a compilation error :

struct : Base { };

但是,当使用时 似乎可行:

#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 ++中,未命名结构是否可以继承?有没有一些有用的示例?

In c++ is it valid for unnamed structures to inherit? Are there any examples where this is userful?

免责声明:我不认为所提供的示例很有用.我很少使用未命名的结构,当我这样做时,它们通常将一些内置的成员变量捆绑在一起,以便为类提供更简洁的接口.问题来自以下观察:成员空间不需要命名的结构

Disclaimer: I'm not pretending the provided example is useful. I rarely use unnamed structs, and when I do they're usually bundling together some built-in member variables, in order to provide a cleaner interface for a class. The question came up from the observation that memberspaces need not be nammed structures

推荐答案

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

Unnamed classes can inherit. This is useful, for example, in situations when you must inherit in order to override a virtual function, but you never need more than one instance of the class, and you do not need to reference the derived type, because a reference to the base type is sufficient.

这里是一个例子:

#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不需要了解任何特定类型-具有虚拟功能的基本类型足以完成此过程.

This code creates four anonymous derivations of Base - one for each operation. When the instances of these derivations are passed to the perform function, the proper override is called. Note that perform does not need to know about any of the specific types - the base type with its virtual function is enough to complete the process.

这是运行上面的代码的输出:

Here is the output of running the above code:

input: 2, 3; output: 5
input: 6, 1; output: 5
input: 6, 7; output: 42
input: 72, 8; output: 9

关于ideone的演示.

这篇关于未命名的结构可以继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:28