考虑以下代码: 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数组,我不允许这样做)
在两个类中使用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);
}
