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

Inheritance: constructor, initialize C like array member of base class in c++11

本文关键字:数组 组成员 基类 构造函数 初始化 C++11 继承      更新时间:2023-10-16

考虑以下代码:

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
};

child的第二个构造函数不起作用。我得到错误"数组必须用大括号括起来的初始值设定项初始化"。如何在不更改基类的情况下在Child中初始化b(例如,使用向量而不是类c数组,我不允许这样做(

Child的构造函数中,bb不是一个数组:由于衰减,它只是一个指针。并且不能用指针初始化数组(Base中的b(。

在两个类中使用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不能修改,您将不得不手动复制元素(在一般情况下,您也可以移动它们,尽管基本类型没有意义(:

#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 << " ";
}
}

在Coliru 上直播

您也可以使用引用来代替std::array,但语法有点复杂:

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