【问题标题】:Unique base class instance唯一的基类实例
【发布时间】:2009-04-26 19:37:30
【问题描述】:

我正在开发一个包含三个类的 C++ dll:比如基类 BaseDerived1Derived2 类。 场景:

class Base
{
   //ctor, dtor, members and methods here
}

class Derived1 : public Base
{
   //ctor, dtor, members and methods here
}

class Derived2 : public Base
{
   //ctor, dtor, members and methods here
}

我正在使用 MS VC++ 2008 Express 创建的 dll,我想在 Turboc++ 下使用它(borland: 非常好的 ide/rad)。

我通过 facotry 方法导出 Derived1,并通过客户端代码,Derived1 生成 Derived2 的实例。 Derived1Derived2 都共享一个包含在另一个 dll 中的指针函数,所以我将该指针函数放在 Base 类下。

这就是问题所在。一旦我创建了Derived1 的一个实例(通过工厂),它可以创建Derived2 的多个实例,Base 类构造函数被调用多次(1 次用于Derived1,多次用于Derived2)。

如何防止 Base 的多个实例?

另一个问题:

在我之前描述的场景中,Derived1 调用Derived2 的多个实例并且Derived1Derived2 都扩展了唯一的公共基类。我问:这是一个糟糕的设计?有没有比我使用的更好的类及其继承层次结构的另一种设计?

【问题讨论】:

    标签: database singleton base


    【解决方案1】:

    您无法阻止 Base 的多个实例。您可以防止指针的多个实例 - 使其成为静态:

    class Base {
        public:
            // save first pointer I get passed
            Base( sometype * p ) {
                if ( myptr == 0 ) {
                   myptr = p;
                }
            }
    
        private:
    
           static sometype * myptr;
    };
    

    在 C++ 源文件中,您需要定义 myptr:

    sometype * Base::myptr = 0;
    

    【讨论】:

    • 由于 Derived* 的每个实例对于 Base::Base() ctor 都是 Base 的实例,因此您无法真正阻止 Base 的多个实例,因为您绝对需要它们。 Neil 将 functionPtr 设为静态来解决您的问题是绝对正确的。
    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2018-01-12
    • 2013-06-25
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多