繁体   English   中英

C ++调用公共基类的私有/受保护函数

[英]C++ Call private / protected function of a common base class

在下面的示例中,有一种很好的方法可以从B::bar()调用A::foo()吗?

class A {
protected:
  void foo() {}
};

class B : public A {
public:
  void bar(A& a) { // edit: called with &a != this
    a.foo(); // does not work
  }
};

除了宣布B成为A的朋友之外,我想不出任何其他事情,但是这可能会因为更多的课而变得非常难看。

有任何想法吗?

是的,您可以使用基类功能。

class A {
protected:
  void foo() {}
  void do_other_foo(A& ref) {
      ref.foo();
  }
};

class B : public A {
public:
  void bar(A& a) { // edit: called with &a != this
    this->do_other_foo(a);
  }
};

为什么要传递A类对象? 你可以这样做:

class B : public A {
public:
  void bar() {
    foo();
  }
};

或者,像这样

class B : public A {
public:
  void bar() {
    A::foo();
  }
};

这是一种给予“受保护”访问的方法,允许任何派生类或对象进行调用。 它使用受保护的令牌类型,解锁特权方法所需:

struct A
{
protected:
    //Zero sized struct which allows only derived classes to call privileged methods
    struct DerivedOnlyAccessToken{};

public:     //public in the normal sense :
    void foo() {}

public:     //For derived types only :
    void privilegedStuff( DerivedOnlyAccessToken aKey );
};

struct B: A
{
    void doPrivelegedStuff( A& a )
    {
        //Can create a token here
        a.privilegedStuff( DerivedOnlyAccessToken() );
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    A a;
    a.foo();
    a.privilegedStuff( A::DerivedOnlyAccessToken() ); // compile error.

    B b;
    b.doPrivelegedStuff( a );

    return 0;
}

这不是我的想法。 我在某处读到了它。 对不起,我不记得是谁的狡猾想法。

我希望编译器可以忽略aKey参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM