简体   繁体   English

使用基类的虚拟方法

[英]Use the base-class virtual method

Starting from this code: 从以下代码开始:

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

If d is a Derived object, can I in some way invoke the foo method defined in the Base class for this object? 如果dDerived对象,我可以以某种方式调用此对象的基类中定义的foo方法吗?

Edit: i mean from the outside, such that d.foo() binds to Base::foo() 编辑:我的意思是从外面,这样d.foo()绑定到Base :: foo()

Specify it explicitly in the call. 在呼叫中明确指定它。

#include <iostream>

class Base{
public:
    virtual void foo(){
      std::cout << "Base" << std::endl;
    }
};
class Derived : public Base{
public:
    void foo(){
      std::cout << "Derived" << std::endl;

    }
};

int main()
{
  Derived d;
  d.Base::foo();
  return 0;
}

Just qualify the call (Assuming that Derived actually inherits from Base , which in your code it doesn't): 只需限定调用即可(假设Derived实际上继承自Base ,而在您的代码中则不是):

Derived d;
d.Base::foo();

Now, while this is doable, it is also quite questionable. 现在,尽管这是可行的,但也值得怀疑。 If the method is virtual, it is meant to be overridden and users should not call a particular override, but the final-overrider , or else they risk breaking class invariants all the way through. 如果该方法是虚拟的,则意味着它应该被重写,并且用户不应调用特定的重写,而应调用final-overrider ,否则他们可能会一直破坏类不变式。

Consider that the implementation of Derived::foo did some extra work needed to hold some invariant, if users call Base::foo that extra work would not be done and the invariant is broken, leaving the object in an invalid state. 考虑到Derived::foo的实现需要做一些额外的工作来保存一些不变性,如果用户调用Base::foo ,则将无法完成额外的工作并且不变式被破坏,从而使对象处于无效状态。

To call it from outside code, you can still explicitly qualify the name in the call: 要从外部代码调用它,您仍然可以在调用中显式限定名称:

#include <iostream>
#include <vector>

struct base { 
    virtual void do_something() { std::cout << "Base::do_something();\n"; }
};

struct derived : public base { 
    virtual void do_something() { std::cout << "derived::do_something();\n"; }
};

int main() {

    derived d;

    d.base::do_something();
    return 0;
}

If you're using a pointer to the object, you'd change that to d->base::do_something(); 如果使用指向对象的指针,则将其更改为d->base::do_something(); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM