【问题标题】:Inheritance: constructor, initialize C like array member of base class in c++11继承:构造函数,像c++11中基类的数组成员一样初始化C
【发布时间】:2019-04-04 10:19:23
【问题描述】:

考虑以下代码:

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 数组,我不允许这样做)

【问题讨论】:

    标签: c++ c++11 inheritance constructor


    【解决方案1】:

    Child的构造函数中,bb不是一个数组:因为decay,它只是一个指针。而且你不能用指针初始化数组(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,因此您必须手动复制元素(在一般情况下,您也可以 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);
    }
    

    【讨论】:

    • @LightnessRacesinOrbit 是的,但知道你不会受伤……可能吗?无论如何,它可以用于较重的类型。
    • 我会改写 - 你不能移动双打。
    • 当然,我的意思是“将std::move 应用于元素”,无论它们的类型是什么。
    • 太棒了!谢谢
    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2017-04-17
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多