[英]Is it possible to call a subclass virtual function from within superclass implementation?
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() {}
virtual void foo() { cout << "My favorite song is:"; bar(); }
virtual void bar() {}
};
class Child : public Parent
{
public:
Child() : Parent() {}
virtual void bar() { cout << "Singing in the Rain"; }
void baz() { Parent::foo(); }
};
int main()
{
Child().baz(); // Outputs "My favorite song is: Singing in the Rain"
return 0;
}
The answer is YES. 答案是肯定的。 The above code works as expected. 上面的代码按预期工作。
Is it possible to call a subclass virtual function from within superclass implementation? 是否可以从超类实现中调用子类虚拟函数?
It is certainly possible. 当然有可能。 But you need to actually establish that inheritance relationship. 但是您实际上需要建立该继承关系。 For instance: 例如:
class Child : public Parent
// ^^^^^^^^
// For instance...
{
public: // Make at least baz() accessible from the outside
// ...
}; // <== And don't forget the semicolon here
And you also need to give member functions in the base class proper accessibility if they have to be invoked by Child
: 而且,如果必须由Child
调用它们,则还需要赋予基类中的成员函数适当的可访问性:
class Parent
{
public: // <== For instance, you could make the member functions public
virtual void foo() { cout << "My favorite song is:"; bar(); }
virtual void bar() {}
}; // <== Do not forget this
For a complete example, see this live demo . 有关完整示例,请参见此实时演示 。
Is it possible to call a subclass virtual function from within superclass implementation? 是否可以从超类实现中调用子类虚拟函数?
Yes, but beware when doing this from within the constructors and destructor, since the type of the object evolves as different constructors/destructors complete. 是的,但是要从构造函数和析构函数中进行此操作,请注意,因为对象的类型会随着不同的构造函数/析构函数的完成而演变。 In particular during the execution of the Parent
constructor/destructor, the type of the object is Parent
regardless of the type of the whole object being constructed. 特别是在执行Parent
构造函数/析构函数期间,无论所构造的整个对象的类型如何,对象的类型都是Parent
。
There are a couple of smells in the code (other than the obvious syntactic errors that the compiler will catch and the lack of inheritance). 代码中有一些气味(除了编译器将捕获的明显语法错误和缺乏继承性)。 For example, foo
is a virtual function in the base, but in the implementation of Child::baz
you are explicitly calling that override (ie disabling dynamic dispatch), which might be intentional or not (you could just call foo()
). 例如, foo
是基础中的虚函数,但是在Child::baz
的实现中,您显式调用了该覆盖(即,禁用动态调度),这可能是有意的(您可以仅调用foo()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.