简体   繁体   English

该继承的类将调用哪个方法(虚拟函数)? C ++

[英]Which method will this inherited class call (virtual function)? c++

Say I have a base class 说我有一个基础班

class Base
{

public:
void A() {do stuff};
void B() {A(); do stuff};
};

and a derived class 和派生类

class Derived : public Base
{
public:
void A() {do things}
};

Derived derived1;
derived1.B();

will B call A of the base class or the A of the derived class? B会调用基类的A还是派生类的A?

I suspect B will call the A of the base class, and that in order for it to use the new redefined A, I have to make it virtual: 我怀疑B将调用基类的A,并且为了使其使用新的重新定义的A,我必须将其虚拟化:

class Base
{

public:
virtual void A() {do stuff};
void B() {A(); do stuff};
};

Is that correct? 那是对的吗? Is that what virtual functions are used for? 那是用于虚拟功能吗?

是的,在两个方面都正确...

try this 尝试这个

class Base
{
public:
virtual void A() {do stuff};
void B() { do stuff};
};

class Derived : public Base
{
public:
void A() {do things}
void B() {do things}
};

and

Derived d;
Base *p = &d;
p->A();
p->B();

function B will not be overrided 功能B将不会被覆盖

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

相关问题 如何为从一个继承而来的所有创建的对象调用虚函数? C++ - How to call virtual function for all created objects which are inherited from the one? C++ C ++从多重继承的模板类中调用虚拟方法 - C++ Calling a virtual method from a multiply inherited template class C ++继承的虚方法仍然使用基类实现 - C++ Inherited Virtual Method Still Uses Base Class Implementation C ++在子类中调用虚方法 - C++ call virtual method in child class 调用从基础 class 继承的 class 的方法。 C++ - Call a method of the inherited class from the base class. C++ C++ memory 布局继承虚拟 class - C++ memory layout of inherited virtual class 如何覆盖在C ++函数内部的另一个类中的一个类中定义的虚拟方法 - How to overwrite a virtual method defined in a class in another class which is inside a function in C++ Boost Python:无法调用C ++虚拟函数,该函数在Python派生类中被覆盖 - Boost Python: Fails to call a C++ virtual function, which is overridden in a Python derived class C ++调用子类而不是基类的虚拟方法 - C++ Call virtual method of child class instead of base class 来自私有继承类的C ++虚拟函数,在派生类声明中提升为公共 - C++ virtual function from privately inherited class, promoted to public in derived class declaration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM