如果你想从它的派生类调用基类的函数,你可以简单地在重写的函数内部调用并提到基类名称(如Foo::printStuff())。
代码在这里
#include <iostream>
using namespace std;
class Foo
{
public:
int x;
virtual void printStuff()
{
cout<<"Base Foo printStuff called"<<endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
cout<<"derived Bar printStuff called"<<endl;
Foo::printStuff();/////also called the base class method
}
};
int main()
{
Bar *b=new Bar;
b->printStuff();
}
同样,您可以在运行时确定使用该类的对象(派生或基类)调用哪个函数。但这要求您在基类中的函数必须标记为虚拟。
下面的代码
#include <iostream>
using namespace std;
class Foo
{
public:
int x;
virtual void printStuff()
{
cout<<"Base Foo printStuff called"<<endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
cout<<"derived Bar printStuff called"<<endl;
}
};
int main()
{
Foo *foo=new Foo;
foo->printStuff();/////this call the base function
foo=new Bar;
foo->printStuff();
}