有没有一种方法来调用,将重写对象的基类的方法? (C ++)(Is there a way to

2019-09-01 02:00发布

我知道有些语言允许这一点。 是否有可能在C ++?

Answer 1:

是:

#include <iostream>

class X
{
    public:
        void T()
        {
            std::cout << "1\n";
        }
};

class Y: public X
{
    public:
        void T()
        {
            std::cout << "2\n";
            X::T();             // Call base class.
        }
};


int main()
{
    Y   y;
    y.T();
}


Answer 2:

class A
{
  virtual void foo() {}
};

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


Answer 3:

是的,只要指定的基类的类型。

例如:

#include <iostream>

struct Base
{
    void func() { std::cout << "Base::func\n"; }
};

struct Derived : public Base
{
    void func() { std::cout << "Derived::func\n"; Base::func(); }
};

int main()
{
    Derived d;
    d.func();
}


文章来源: Is there a way to call an object's base class method that's overriden? (C++)
标签: c++ oop