覆盖子类中的数组大小

Rya*_*uck 2 c++ arrays inheritance

我有一个数组作为类的成员.在子类中,我想重新定义具有不同大小的数组.我想这样做是因为我期望制作许多子类,每个子类只需要它所需的数组大小,仅此而已.

class Foo
{
    Foo() {ivar = 1};
    int thisArray[2];
    int ivar;
}

class Bar : public Foo
{
    Bar() {ivar = 3};
    int thisArray[4];
}

int main()
{
    Foo myFoo;
    Bar myBar;

    Foo fooCollection[] = {myFoo,myBar};

    cout << "myFoo array size = " << sizeof(myFoo.thisArray)/sizeof(int) << endl;
    cout << "myBar array size = " << sizeof(myBar.thisArray)/sizeof(int) << endl;

    for (int n=0;n<2;n++)
    {
        cout << "fooCollection[" << n << "] array size = ";
        cout << sizeof(fooCollection[n].thisArray)/sizeof(int) << endl;
    }
    for (int n=0;n<2;n++)
    {
        cout << "fooCollection[" << n << "] ivar = ";
        cout << fooCollection[n].ivar << endl;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的结果是:

myFoo array size = 2
myBar array size = 4
fooCollection[0] array size = 2
fooCollection[1] array size = 2
fooCollection[0] ivar = 1
fooCollection[1] ivar = 3
Run Code Online (Sandbox Code Playgroud)

我得到的,因为我声明数组对象的类的对象Foo,是指myBar内的范围将引用myBar,就好像它是一个Foo,因此解释的大小thisArray等同于2.我也明白了,为什么ivar出来它的方式.

有没有办法影响的大小thisArray的内Bar类,所以它的"正确"大小的数组内公认的Foo对象?我会使用矢量,但他们在arduino平台上并不友好.我也可以简单地在Foo类中创建大小为100的数组,但我试图意识到内存分配.

pad*_*ddy 9

您可以模拟基类:

template <size_t Size>
class FooBase
{
    // etc....
    int thisArray[Size];
};

class Foo : public FooBase<2> { ... };

class Bar : public FooBase<4> { ... };
Run Code Online (Sandbox Code Playgroud)

当然,这只适用于所有内容都来自的地方FooBase- 也就是说,您没有一个派生自Bar哪个类需要不同数组大小的类.

另外,正如在评论中所说的那样,如果你需要将它们保存在数组中,则需要存储指针.

Foo myFoo;
Bar myBar;
Foo * fooCollection[] = { &myFoo, &myBar };
Run Code Online (Sandbox Code Playgroud)

哎呀,在那里我假设它Bar来源于Foo它不再存在.如果你想要一个没有模板化的公共基础,你需要FooBase<Size>从另一个基础派生模板化的类FooType,现在使用一个数组FooType.我认为这会奏效.

class FooType {
  public:
      // etc...
      virtual size_t GetSize() const = 0;
};

template <size_t Size>
class FooBase : public FooType
{
  public:
    // etc...
    virtual size_t GetSize() const { return Size; }

  protected:
    // etc....
    int thisArray[Size];
};
Run Code Online (Sandbox Code Playgroud)

然后:

FooType *fooCollection[] = { &myFoo, &myBar };
Run Code Online (Sandbox Code Playgroud)