[英]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.