简体   繁体   English

如何在子类中重新定义数组大小?

[英]How can I redefine array size in a subclass?

I have a base class in which I define an array of structs (of base types) and some methods that act on its objects;我有一个基础 class ,我在其中定义了一个结构数组(基本类型)和一些作用于其对象的方法; I never instantiate directly this class, just created varius sublasses of it.我从不直接实例化这个 class,只是创建了它的各种子类。 Now, in each subclass I would like to redefine the array size to the subclass particular needs.现在,在每个子类中,我想将数组大小重新定义为子类的特定需求。

Consider that I would like to avoid dynamic allocation in order to keep the program more dependable and because I like to see at compile time the amount of memory I'm using with my design.考虑到我想避免动态分配以使程序更可靠,并且因为我喜欢在编译时查看我在设计中使用的 memory 的数量。

I tryed by simply redefining the array in the subclasses;我尝试简单地重新定义子类中的数组; the compiler (I use Arduino IDE) does not complain about it but, from the amount of memory used reported by the compiler, I see that actually both arrays exist (the one defined in base class and the one "redefined" in the subclass) so it seems this is not the way to do it. the compiler (I use Arduino IDE) does not complain about it but, from the amount of memory used reported by the compiler, I see that actually both arrays exist (the one defined in base class and the one "redefined" in the subclass)所以看来这不是这样做的方法。

I found a suggestion about using templates but It hasn't received much approval, and because I read that templates are about making a class manage different data types, I think my problem of wanting just a different array size could have a more simple solution.我发现了一个关于使用模板的建议,但它没有得到太多的认可,因为我读到模板是关于让 class 管理不同的数据类型,我认为我想要一个不同的数组大小的问题可能有一个更简单的解决方案。

What is the correct way to obtain what I want?获得我想要的东西的正确方法是什么?

Here is an example of my (wrong) code:这是我的(错误)代码的示例:

typedef struct {
    char val1;
    int val2;
} DataItem;


class BaseClass {
    DataItem dataItems[5];
};

class Sublass_A : public BaseClass {
    DataItem dataItems[50];
};

class Sublass_B : public BaseClass {
    DataItem dataItems[15];
};

With template, you might do something like:使用模板,您可能会执行以下操作:

template <std::size_t N>
class ItemsArray {
    DataItem dataItems[N];
};

using classA = ItemsArray<50>;
using classA = ItemsArray<15>;

Here is the initial code of my question, corrected following the @Jarod42's answer .这是我的问题的初始代码,在@Jarod42 的回答之后更正。

typedef struct {
    char val1;
    int val2;
} DataItem;


template <size_t N = 5> // 5 is the default value if the size is not specified
class BaseClass {
    DataItem dataItems[N];
};

class Sublass_A : public BaseClass<50> {
};

class Sublass_B : public BaseClass<15> {
};

It compiles correctly and tests using sizeof() on the subclasses objects reported the expected sizes of the array.它正确编译并在子类对象上使用 sizeof() 进行测试,报告了数组的预期大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM