假设我有一个基类和一个派生类:
struct A
{
void foo()
{
std::cout << "Do one thing." << std::endl;
}
};
struct B: public A
{
void foo()
{
std::cout << "Do another thing." << std::endl;
}
};
B myB;
myB.foo();
通常这会打印Do another thing.
,但如果我希望foo()
也运行基座foo()
并打印:
Do one thing.
Do another thing.
答案 0 :(得分:3)
在A::foo()
中调用B::foo()
,这样基类的函数将首先执行,然后其余的派生类函数执行。
struct A
{
void foo()
{
std::cout << "Do one thing." << std::endl;
}
};
struct B : public A
{
void foo()
{
A::foo();
std::cout << "Do another thing." << std::endl;
}
};