如何通过指向派生类的基类指针调用Base类方法

时间:2009-07-16 08:45:19

标签: c++ polymorphism

class Base
{
  public:
    virtual void foo()
    {}
};

class Derived: public Base
{
  public:
    virtual void foo()
    {}
};

int main()
{
    Base *pBase = NULL;
    Base objBase;
    Derived objDerived;

    pBase = &objDerived;
    pBase->foo();

    /*Here Derived class foo will be called, but i want this to call 
    a base class foo. Is there any way for this to happen? i.e. through 
    casting or something? */
}

3 个答案:

答案 0 :(得分:30)

pBase->Base::foo()

答案 1 :(得分:10)

上面的两个回答都是正确的......但要小心,如果你需要这样做,也许你对概念或设计有很大的问题......

答案 2 :(得分:7)

您可以通过范围解析运算符::

来完成

这样的事情:

pBase->Base::foo()