2016-03-23 53 views
1

讓我們看看下面的代碼:基類方法的別名

#include <iostream> 

class Base 
{ 
public: 
    void foo() //Here we have some method called foo. 
    { 
     std::cout << "Base::foo()\n"; 
    } 
}; 

class Derived : public Base 
{ 
public: 
    void foo() //Here we override the Base::foo() with Derived::foo() 
    { 
     std::cout << "Derived::foo()\n"; 
    } 
}; 

int main() 
{ 
    Base *base1 = new Base; 
    Derived *der1 = new Derived; 
    base1->foo(); //Prints "Base::foo()" 
    der1->foo(); //Prints "Derived::foo()" 
} 

如果我有上述類別,我可以從任何BaseDerived類實例調用foo方法,這取決於我需要什麼::foo()。但是有一些問題:如果我需要Derived類實例,但是我確實需要從這個實例調用Base::foo()方法?

這個問題的解決可能是下一個: 我下一個方法粘貼到派生

public: 
void fooBase() 
{ 
    Base::foo(); 
} 

類和調用Derived::fooBase()當我需要從派生類的實例Base::foo()方法。

問題是我能做到這一點使用using指令像這樣的東西:

using Base::foo=fooBase; //I know this would not compile. 

回答

2
der1->Base::foo(); //Prints "Base::foo()" 

您可以使用作用域分辨率調用基類方法來指定函數版本並解決在不想使用默認分辨率時有用的歧義。

類似(不完全是相同的情況下)例如提及@cppreference

struct B { virtual void foo(); }; 
struct D : B { void foo() override; }; 
int main() 
{ 
    D x; 
    B& b = x; 
    b.foo(); // calls D::foo (virtual dispatch) 
    b.B::foo(); // calls B::foo (static dispatch) 
}