如何为派生类传播朋友

问题描述 投票:23回答:7

我希望有一个类层次结构,并且只能在Factory中创建对象。

例:

class Base
{
    protected:
        Base(){};
        virtual void Init(){};

    friend class Factory;
};

class SomeClass : public Base
{
    public://I want protected here! Now it's possible to call new SomeClass from anywhere!
        SomeClass(){};
        void Init(){};
};

class Factory
{
    public:
        template<class T>
        T* Get()
        {
            T* obj = new T();
            obj->Init();

            return obj;
        }
};

int main()
{
    Factory factory;
    SomeClass *obj = factory.Get<SomeClass>();
}

我的问题是我希望能够只从Factory创建对象,但我不想在从Base派生的每个类中声明friend class Factory

有没有办法在派生类中传播朋友?有没有其他方法来实现这种行为?

c++ friend
7个回答
11
投票

不,这是故意不可能的。

是封装问题。

假设有一个管理任何密码的类“PswClass”,这是与其他类级联的朋友:如果我从PswClass继承:

 class Myclass : public PswClass {
     .......
 }

通过这种方式,我可以访问它将是私有的字段。


2
投票

友谊既不是遗传也不是传递,如下所述:friend class with inheritance

经过一些实验,并利用这个hack How to setup a global container (C++03)?,我想我找到了一种方法,赋予“工厂”创建对象的唯一权利。

这是一个快速而肮脏的代码。 (向下滚动以查看黑客攻击。)

class Object {};

class Factory {
public:
    // factory is a singleton
    // make the constructor, copy constructor and assignment operator private.
    static Factory* Instance() {
        static Factory instance;
        return &instance;
    }

    public: typedef Object* (*CreateObjectCallback)(); 
    private: typedef std::map<int, CreateObjectCallback> CallbackMap; 

public: 
    // Derived classes should use this to register their "create" methods.
    // returns false if registration fails
    bool RegisterObject(int Id, CreateObjectCallback CreateFn) {
        return callbacks_.insert(CallbackMap::value_type(Id, createFn)).second; 
    }

    // as name suggests, creates object of the given Id type
    Object* CreateObject(int Id) {
        CallbackMap::const_iterator i = callbacks_.find(Id); 
        if (i == callbacks_.end()) { 
            throw std::exception(); 
        } 
        // Invoke the creation function 
        return (i->second)(); 
    }

    private: CallbackMap callbacks_; 
};

class Foo : public Object {
    private: Foo() { cout << "foo" << endl; }
    private: static Object* CreateFoo() { return new Foo(); }


public:
    static void RegisterFoo() {
        Factory::Instance()->RegisterObject(0, Foo::CreateFoo);     
    }
};

class Bar : public Object {
    private: Bar() { cout << "bar" << endl; }
    private: static Object* CreateBar() { return new Bar(); }

public:
    static void RegisterBar() {
        Factory::Instance()->RegisterObject(1, Bar::CreateBar);     
    }
};

// use the comma operator hack to register the create methods
int foodummy = (Foo::RegisterFoo(), 0);
int bardummy = (Bar::RegisterBar(), 0);

int main() {
    Factory::Instance()->CreateObject(0); // create foo object
    Factory::Instance()->CreateObject(1); // create bar object
}

1
投票

不,没有办法从基类继承friend声明。但是,如果你制作Base构造函数private,如果没有Factory帮助,将无法创建派生类的实例。


1
投票

正如其他人已经说过的那样,友谊不是可继承的。

这看起来像是“抽象工厂”模式的一个很好的候选人。

假设从基数派生的“SomeClass”是多态的。声明一个抽象工厂库,它创建Base对象。从base派生每个具体工厂,覆盖基础创建方法......

http://en.wikipedia.org/wiki/Abstract_factory_pattern为例


0
投票

你不能这样做。这样做是为了保护封装。看到这篇文章:Why does C++ not allow inherited friendship?


0
投票

为了将来的参考,另一个想法来自OP和我之间的chat,它只使用friend作为OP想要的。当然,这不是一种通用的解决方案,但在某些情况下可能会有用。

下面的代码是一个最小的代码,显示了基本的想法。这需要“集成”到Factory代码的其余部分。

class Factory;

class Top { // dummy class accessible only to Factory
private:
    Top() {}
friend class Factory;
};

class Base {
public:    
    // force all derived classes to accept a Top* during construction
    Base(Top* top) {}  
};

class One : public Base {
public:    
    One(Top* top) : Base(top) {}
};

class Factory {
    Factory() {
        Top top;  // only Factory can create a Top object
        One one(&top);  // the same pointer could be reused for other objects
    }
};

0
投票

这不可能。正如其他人所说,友谊不是继承的。

另一种方法是使所有类层次结构构造函数受到保护,并将工厂函数/类作为朋友添加到您感兴趣的所有类中。

© www.soinside.com 2019 - 2024. All rights reserved.