0

我有一个Framework用户可以通过重写一些接受对Object. 不允许用户Object::do_something()从任何这些函数中调用,除了Framework::f(). 为了实现这个要求,我必须引入一个Helper具有静态成员函数的类,如下例所示。我想知道是否有更短或更清洁的东西。

class Object;

struct Framework { // the interface is fixed
protected:
    virtual void f(Object& o); // f is allowed to call o.do_something()
    virtual void g(Object& o); // g is not allowed to call o.do_something()
    friend class Helper;
};

class Helper { // Helper class to make things work as wanted
    friend class Object;
    friend void Framework::f(Object&);
    static void helper(Object&);
};

class Object {
    void do_something() {}
    friend void Helper::helper(Object&);
  public:
    void do_something_else() {}  
};

void Helper::helper(Object& o) {o.do_something();}

// user implementation
void Framework::f(Object& o) {Helper::helper(o);}
void Framework::g(Object& o) {o.do_something_else(); /*Helper::helper(o);*/} // o.do_something() denied
4

1 回答 1

0

可能您应该像为方法所做的那样声明void f(Object& o)为类。friendObjectvoid Helper::helper(Object&)

于 2013-06-09T16:42:42.223 回答