【问题标题】:Is there any way to put in a undefined-sized array and be inherited as a static one?有没有办法放入一个未定义大小的数组并作为静态数组继承?
【发布时间】:2014-11-14 06:39:18
【问题描述】:

我想知道是否有办法让类/结构中的数组没有精确的设置值,所以当它被继承时,它可能具有与其他结构不同的值。在这个例子中:

struct foo
{
    virtual int test[];
};
struct bar : foo
{
    int test[3];
};
struct bars : foo
{
    int test[5]
};

在此示例中,我尝试在 foo 类中定义一个具有 virtual 关键字的新 int 数组。如您所见,bar 的测试数组大小为 3,但在bars 的测试数组大小为 5。但是,当我尝试将 foo 继承到 barbars 时,它失败了并给我一个错误:invalid base class

编辑:抱歉,我的帖子不是很清楚。我试图最好地解释一个未知大小的数组,但不知何故最终得到了一些更令人困惑的东西。另外,对于要说使用std::vector 的人,请重新阅读我上面的编辑

【问题讨论】:

  • virtual int test[]; 不是虚拟函数

标签: c++ arrays inheritance struct


【解决方案1】:

有解决办法吗?更好的是,有没有比数组更有效的方法,它允许从继承的动态数组成为新的静态数组?

在基类中使用 std::vector...并使其受到保护。

【讨论】:

    【解决方案2】:

    不确定您要完成什么。无论如何,您都可以使用;

    struct foo
    {
        foo(int* t) : test(t) {}
        int* test;
    };
    struct bar : foo
    {
        bar() : foo(derived_test) {}
    
        int derived_test[3];
    };
    

    不过使用std::vector<int> 会好很多。

    struct foo
    {
        foo(size_t size) : test(size) {}
        std::vector<int> test;
    };
    struct bar : foo
    {
        bar() : foo(3) {}
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-05
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多