抽象基类中的静态const变量 [英] static const variables in abstract baseclass

查看:64
本文介绍了抽象基类中的静态const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象的基类,它用于派生一些类。
这些类的某些属性在所有类之间共享,并且这些属性应该不可修改。

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.

要使变量在所有10个类中共享,我将使其

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(){};
};

这很好,tot_index将包含实例化的类数,并且索引是该类的唯一标识符每个类。

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

我遇到的问题是,在运行时设置了* anArray和派生类的数量,并且在实例化这些类之后,我不想修改这些值。

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.

我有点困惑:

1)我应该在哪里设置* anArray值?

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

2)如果变量是不可修改的,那么我应该将其设置为const。但是,如果我不知道编译时的值是什么,该如何将其设置为const?

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?

推荐答案

而不是使用静态变量,有一些模式可以实现此目的。

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).

另一个更漂亮的解决方案可能是某种工厂模式,例如GoF抽象工厂。

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

编辑:
另外,有关文档的注释,请参见: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

:)

这篇关于抽象基类中的静态const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆