当前位置 : 主页 > 手机开发 > 其它 >

继承:构造函数,初始化C,类似于c 11中基类的数组成员

来源:互联网 收集:自由互联 发布时间:2021-06-19
考虑以下代码: struct Base //in my real scenario Base class can not be changed{ int a; double b[10];};struct Child : Base{ Child(int aa, double bb[10]) : Base{aa} {} //This works fine Child(int aa, double bb[10]) : Base{aa, bb} {} //
考虑以下代码:

struct Base //in my real scenario Base class can not be changed
{
    int a;
    double b[10];
};

struct Child : Base
{
    Child(int aa, double bb[10]) : Base{aa} {}     //This works fine
    Child(int aa, double bb[10]) : Base{aa, bb} {} //this is not working
};

孩子的第二个构造函数不起作用.我得到错误“数组必须用括号封闭的初始化程序初始化”.
如何在不更改Base类的情况下初始化Child中的b(例如使用vector而不是c-like数组,我不允许这样做)

在Child的构造函数中,bb不是数组:因为 decay,它只是一个指针.而且你不能用指针初始化一个数组(b在Base中).

在两个类中使用std::array而不是原始数组将解决您的问题:

struct Base
{
    int a;
    std::array<double, 10> b;
};

struct Child : Base
{
    Child(int aa, std::array<double, 10> bb) : Base{aa, bb} {}
};

但是,由于您提到Base无法修改,您必须手动复制元素(在一般情况下,您也可以使用move,但基本类型没有意义):

#include <array>
#include <algorithm>
#include <iostream>

struct Base {
    int a;
    double b[10];
};

struct Child : Base {
    Child(int aa, std::array<double, 10> bb) : Base{aa} {
        std::copy(bb.begin(), bb.end(), b);
    }
};

int main() {
    auto child = Child(3, {2, 3, 4});

    for (auto it : child.b) {
        std::cout << it << " ";
    }
}

Live on Coliru

您也可以使用引用而不是std :: array来实现,但语法有点复杂:

Child(int aa, double const (&bb)[10]) : Base{aa} {
    std::copy(&bb[0], &bb[10], b);
}
网友评论