static const variables in abstract baseclass

纵饮孤独 提交于 2020-01-05 07:17:13

问题


I've got a abstract baseclass, this is used for deriving some classes. Some properties of these classes are shared among all classes, and these should be unmodifiable.

To make a variable shared among all 10 classes I'll make it static.

class ABC{
public:
  static int *anArray;
  int index;
  static int tot_index;
  virtual void print()=0;
  ABC(){index=tot_index++;};
  virtual ~ABC(){};
};

This works fine, tot_index will contain the number of classes instantiated, and the index is the unique indentifier for each class.

The issue I have is that the *anArray, and number of derived classes is set at runtime, and after the classes have been instantiated I don't want to modify these values.

I'm abit puzzled by:

1) Where should I set the *anArray value? Just in some random of the derived class's?

2) If a variable should be unmodifiable, then I should set it to const. But If I don't know what the value is at compile time, how do I set it to const?


回答1:


Instead of using static variables there are some patterns that could achieve this.

The easiest to implement, albeit not the best for many reasons, would be putting your shared variables in a singleton base class (ref: GoF Singleton pattern).

Another, prettier solution could be some factory pattern, like the GoF Abstract Factory.

Edit: Also, for doc's comment, see: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

:)



来源:https://stackoverflow.com/questions/13905704/static-const-variables-in-abstract-baseclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!