2010-12-19 107 views
3

下面的示例中有沒有一種很好的方式可以從B::bar()調用A::foo()C++調用通用基類的私有/受保護函數

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朋友其它任何東西,但可能變得相當難看多用一些類。

任何想法?

+0

爲什麼'B :: bar'需要調用'A :: foo'?如果'A :: foo'受到保護,這應該意味着只有'A'類型的對象和從'A'派生的任何類型才能夠調用它。如果你確實需要從一個不相關的類調用'A :: foo',可能它不應該被保護。 – 2010-12-19 20:57:26

+0

什麼是問題? – 2010-12-19 20:57:56

+0

當'B'是'A'類型時,將'A'實例傳遞給'B'的原因是什麼? – birryree 2010-12-19 20:58:11

回答

4

是的,你可以使用一個基類的功能。

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); 
    } 
}; 
+0

當然是在工作。不是很好,但可能是最好的解決方案。謝謝! – 2010-12-20 00:12:49

3

你爲什麼要傳遞類型A的對象?你可以這樣做:

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

,或者類似這樣的

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

我並不打算在'* this'上使用'B :: bar',而是在其他實例上(實際上在A的其他子類中)使用'B :: bar'。 – 2010-12-19 21:00:58

+0

@lucas聽起來像是一個設計問題。爲什麼foo()受到保護? – 2010-12-19 21:03:17

+0

看到我上面的帖子,我不想讓我的圖書館之外的類/函數使用它。 – 2010-12-19 21:06:26

1

下面就給人「保護」之類訪問,允許通過任何派生類或對象調用的方法。 它使用一個受保護的令牌類型,需要取消鎖定特權方法:

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參數。

+0

非常好的主意,非常感謝! – 2012-06-24 20:45:29

相關問題