下面是代碼樣本惹惱我:如何從派生類訪問基類中的受保護方法?
class Base {
protected:
virtual void foo() = 0;
};
class Derived : public Base {
private:
Base *b; /* Initialized by constructor, not shown here
Intended to store a pointer on an instance of any derived class of Base */
protected:
virtual void foo() { /* Some implementation */ };
virtual void foo2() {
this->b->foo(); /* Compilator sets an error: 'virtual void Base::foo() is protected' */
}
};
如何訪問到受保護的overrided功能?
感謝您的幫助。 :o)
我不認爲你的實施是完全正確的。爲什麼你有一個Base的實例作爲成員變量? this-> b-> foo()會嘗試調用一個純粹的虛擬方法。 – GWW 2011-01-12 18:26:34
這個程序不應該編譯。你不能實例化一個抽象類....除非`b`指向從`Base`派生的其他類的實例。 – 341008 2011-01-12 18:34:58
我省略了精確性:Derived :: b屬性用於存儲基類 – 2011-01-13 10:44:15