如何改变一个类中的所有实例的行为 [英] How to change a behavior for all instances of a class in a header only class

查看:77
本文介绍了如何改变一个类中的所有实例的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于只在头中定义的类,我需要为该类的所有实例使用一个方法的特殊行为。它应该取决于默认值,可以在运行时期间随时更改。由于我不想要一个工厂类或中央管理类,我想出了这个想法:

For a class, which is only defined in a header, I need a special behavior of one method for all instance of the class. It should be depending on a default value, which can be changed any time during runtime. As I do not want a factory class nor a central management class I came up with that idea:

class MyClass
{
public:
    void DoAnything() // Methode which should be act depending on default set.
    {
        // Do some stuff
        if(getDefaultBehaviour())
        {
            // Do it this way...
        }
        else
        {
            // Do it that way...        
        }
    }

    static bool getDefaultBehaviour(bool bSetIt=false,bool bDefaultValue=false)
    {
        static bool bDefault=false;
        if(bSetIt)
            bDefault=bDefaultValue;
        return bDefault;
    }
};

它工作,但它看起来有点尴尬。我想知道是否有一个更好的方式遵循同样的意图。
在我想使用它的情况下,软件在启动期间已经创建了该类的实例,并将它们传递到代码的不同部分。最终,程序获得如何处理实例的信息(例如,如何或在哪里使自己持久化)。这个决定不仅会影响新建立的执行个体,还会影响已建立的执行个体。

It works, but it looks a little awkward. I wonder if there is a better way following the same intention. In the case where I want to use it the software already created instances of that class during startup and delivered them to different parts of the code. Eventually the program gets the information how to treat the instances (for e.g. how or where to make themselves persistent). This decision should not only affect new created instances, it should affect the instances already created.

推荐答案

简单的方法来模拟静态数据成员,所以使用变得更自然:

I'd advise to use a simple method to simulate a static data member, so the usage becomes more natural:

class MyClass
{
public:
    // get a reference (!) to a static variable
    static bool& DefaultBehaviour()
    {
        static bool b = false;
        return b;
    }

    void DoAnything() // Methode which should be act depending on default set.
    {
        // Do some stuff
        if(DefaultBehaviour())
        {
            // Do it this way...
        }
        else
        {
            // Do it that way...        
        }
    }
};

其中用户可以随时使用

MyClass::DefaultBehaviour() = true;

这篇关于如何改变一个类中的所有实例的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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