我可以在抽象类中有静态数据成员吗? [英] Can I have static data members in an abstract class?

查看:173
本文介绍了我可以在抽象类中有静态数据成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一系列相关的类,为了能够对其进行管理,我使它们从单个抽象类派生。

I designed a series of related classes, and in order to be able to manage them I made them derive from a single abstract class.

这些类都需要访问到一系列共享资源,我发现自己在每个共享资源中创建了一个指针向量,它们全部相同(它们必须是必须的)。似乎在基类中创建静态成员将使所有派生类都可以访问此向量,这意味着我只需要构建一次(构建后它也不会改变,只需查找即可)。

These classes all need access to a series of shared resources, and I found myself creating a vector of pointers in each, all of them identical (they necessarily must be). It seems like making a static member in the base class would give all of the derived classes access to this vector, meaning I need only build it once (it's not going to change either after it's been built, just looked up).

我的问题是,这是否可以,如果可以,如何在不从派生类之一调用填充向量方法的情况下构建它?

My question is if this is ok, and if so, how can I then build it, without calling a 'fill the vector' method from one of the derived classes?

我的想法是做类似的事情

My thinking was to do something like

class Resource {};

enumR {RES0, RES1};

class AbstractClass
{
    public:
        virtual void OnInit() = 0;
        void static fillVector(Resource* pResource, enumR Resourcename)
            {lResource[Resourcename]=pResource;};
    protected:
        static vector<Resource*> lResource;
};

vector<Resource*> AbstractClass::lResource;

int main()
{
    Resource res0, res1;
    AbstractClass::fillVector(&res0, RES0);
    AbstractClass::fillVector(&res1, RES1);

    return 0;
};

然后,当我实例化一个从AbstractClass派生的任何类的对象时,我将可以访问lResource向量,这就是我想要的。

Then when I instantiate an object of any class derived from AbstractClass, I'd have access to the lResource vector, which is what I want.

这项工作可以吗?太恐怖了吗?可以吗?

Would this work? Is it horrible? Is it ok?

推荐答案

更好的解决方案是只创建带有矢量的对象,然后实例化一次并给其他类一个指针或对其的引用。除非有必要,否则绝对应避免使用静态数据,而这是不必要的。

The better solution would be to just make an object with the vectors in and then only instantiate it once and give the other classes a pointer or reference to it. Static data should be absolutely avoided unless necessary and this just isn't necessary.

这篇关于我可以在抽象类中有静态数据成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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