问题描述
是否只需在继承层次结构中一次将方法定义为virtual
即可使多态性起作用.在下面的示例中,Der :: f未定义为virtual
,但是d2->f();
打印 der2 我正在使用VS IDE(可能只是那里...)
Is it sufficient to define the method once to be virtual
in the inheritance hierarchy to make polymorphism to work.In the following example Der::f is not defined to be virtual
but d2->f();
prints der2I am using VS IDE (may be it is only there...)
class Base
{
public:
virtual void f() { std::cout << "base"; }
};
class Der : public Base
{
public:
void f() { std::cout << "der"; } //should be virtual?
};
class Der2 : public Der
{
public:
void f() { std::cout << "der2"; }
};
int main()
{
Der* d2 = new Der2();
d2->f();
}
推荐答案
是的,如果您在Base类中将方法定义为仅虚拟方法,则多态性将起作用.但是,这是我在一些大型项目中遇到的惯例,总是在派生类的方法声明中重复虚拟关键字.当您处理具有复杂类层次结构(许多继承级别)的许多文件时,这些类在单独的文件中声明,这可能会很有用.这样,您就不必在添加另一个派生类时通过查找基类声明来检查哪个方法是虚拟的.
Yes, polymorphism will work if you define method as a virtual only in your Base class. However, it is a convention I came across working with some large projects to always repeat virtual keyword in method declarations in derived classes. It may be useful when you are working with a lot of files with complex class hierarchy (many inheritance levels), where classes are declared in separate files. That way you don't have to check which method is virtual by looking for base class declaration while adding another derived class.
这篇关于一次将方法定义为继承层次结构中的虚拟方法,以使多态性起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!