覆盖子类中的数组大小 [英] Override array size in subclass
问题描述
我有一个数组作为类的成员.在子类中,我想用不同的大小重新定义数组.我之所以要这样做,是因为我期望创建许多子类,每个子类仅具有所需的数组大小,仅此而已.
I have an array as a member of a class. In a subclass, I would like to re-define the array with a different size. I want to do this because I anticipate making many subclasses, each with only the array size it needs, and nothing more.
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;
}
}
我的结果是:
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
我明白了,因为我将数组对象声明为类 Foo
的对象,因此在该范围内引用 myBar
的对象将引用 myBar
好像它是一个 Foo
,因此将 thisArray
的大小解释为等于2.我也理解为什么 ivar
会以这种方式出现.
I get that, since I declare the array objects as objects of class Foo
, that referring to myBar
within that scope would reference myBar
as though it was a Foo
and consequently interpret the size of thisArray
as equivalent to 2. I also understand why ivar
comes out the way it does.
是否有一种方法可以影响 Bar
类中 thisArray
的大小,以便可以在 Foo数组中识别其正确"的大小代码>对象?我会使用向量,但是在arduino平台上它们并不友好.我也可以简单地在Foo类中使数组的大小为100,但是我试图意识到内存分配的问题.
Is there a way to affect the size of thisArray
within the Bar
class so its "correct" size can be recognized within an array of Foo
objects? I would use a vector, but they are not friendly on the arduino platform. I could also simply make the array within the Foo class with a size of 100, but I am trying to be conscious of memory allocation.
推荐答案
执行此操作时: cout<<sizeof(fooCollection [n] .thisArray)/sizeof(int)<<endl;
,因为您没有使用实际的多态性,所以无法知道 thisArray
的大小.因此,编译器假定 fooCollection
中的所有元素都是simpy Foo
(静态绑定).
When you do this: cout << sizeof(fooCollection[n].thisArray)/sizeof(int) << endl;
, it is impossible to know the size of thisArray
because you are not using actual polymorphism. So the compiler assumes all elements in fooCollection
are simpy Foo
(static binding).
从使用指针开始:
Foo * fooCollection[] = { &myFoo, &myBar };
并声明一个虚拟成员,该成员将在运行时知道阵列的大小.(动态绑定)
And declaring a virtual member that will know at runtime the size of the array. (dynamic binding)
virtual int size() {return sizeof(thisArray);}
然后重写为:
cout << fooCollection[n]->size()/sizeof(int) << endl;
这篇关于覆盖子类中的数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!