【发布时间】:2014-09-11 00:23:27
【问题描述】:
我有这些课程 A 和 B 等等..
class A : public O
{
static const int _nbItems = 3;
...
};
class B : public O
{
static const int _nbItems_mine_mine = 7800;
...
};
...
它们都继承自 abstract 父类 O,它知道如何管理 Items 集合,并且不会让孩子们玩弄它随心所欲..
class O
{
private:
// The kids won't be able to access this structure directly for it is carefully updated
Item _items[size];
// (I mean.. *truly*, look :)
void update() // called by the clock
{
for(int i(0); i < size; ++i) /* things involving */ _items[i] /*, its environment etc.*/
};
protected:
// They may set their items this way only:
void setItemNo(int id, BuildInformation const& buildInfo)
{
/*
* check whether or not the item has already been added..
* perform everything that must be done to welcome a new item..
* well.. 'so many things the kids do not need to be aware of.
*/
// and then:
_items[id] = Item(buildInfo);
};
// .. retrieve information about the current state of their items this way only:
SomeInformation getItemState(int id) const {return _items[id].currentState();};
// .. and eventually change some of their properties this way only:
void setItemProperty(int id, Property const& newProperty)
{
/* checks, updates, eventual repercussions on other items and the environment */
_items[id].setProperty(newProperty);
};
};
我可以使用什么作为O::_items 的结构,以获取所有存储在堆栈 上的Items?这应该是可能的,因为它的大小最终在编译时就知道了,不是吗?
换一种说法:我怎样才能让*nbItems* 的信息以一种让编译器知道它们仍然是文字常量的方式到达O::size,即使在O 中还没有定义?
PS:在编写O 时,我显然不知道它有一天可能拥有的所有可能的派生类。
【问题讨论】:
-
有什么理由
O不能是在size上参数化的模板类吗? -
将
O设为模板。template<size_t size> class O { Item _item[size]; },那么你的派生类可以派生自O<3>或O<7800>。 -
@CharlesBailey:哦,也许不是!让我进一步考虑这个.. :)
标签: c++ arrays inheritance literals