如何更改仅限标题类中的所有类实例的行为

时间:2014-01-07 16:14:19

标签: c++ c++11

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

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;
    }
};

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

2 个答案:

答案 0 :(得分:2)

我建议使用一种简单的方法来模拟静态数据成员,因此使用变得更自然:

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;

答案 1 :(得分:0)

我要感谢Daniel Frey的答案,我已经将其标记为最佳答案。我想根据Frey的答案添加我的最终解决方案。该类由一些c ++初学者使用。正如我告诉他们总是使用getter和setter方法一样,Frey描述的方式看起来对初学者来说非常复杂(“uuuh,我可以给函数一个值?!?!”)。所以我写了这样的课程:

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

    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...        
        }
    }
};

对于用户来说,我现在看起来像一个普通的getter和setter。