覆盖非虚函数和虚函数的区别是什么?

What is the difference from overwriting a nonvirtual function and a virtual?

本文关键字:函数 是什么 区别 覆盖      更新时间:2023-10-16

在c++中:覆盖非虚函数和覆盖虚函数有什么区别?

virtual:

class Base {
    virtual void Foo() { std::cout << "Foo in Base" << std::endl;}
};
class Derived : public Base {
    virtual void Foo() { std::cout << "Foo in Derived" << std::endl;}
};
// in main()
Derived* d = new Derived();
d->Foo(); // prints "Foo in Derived"
Base* b = new Derived();
b->Foo(); // prints "Foo in Derived"

和不

(相同的代码,但省略virtual):

// in main() 
Derived* d = new Derived();
d->Foo(); // prints "Foo in Derived"
Base* b = new Derived();
b->Foo(); // prints "Foo in Base"

所以不同之处在于,没有virtual,就没有真正的运行时多态性:调用哪个函数由编译器决定,取决于调用它的指针/引用的当前类型。

对于virtual,对象维护一个虚函数列表(vtable),它在其中查找要调用的函数的实际地址——在运行时,每次调用它的虚成员。在这个示例中,Derived构造函数隐式地修改了Foo的条目,使其指向被覆盖的函数,因此通过Base指针调用Foo并不重要。

重写虚函数将确保在运行时评估对象的类型,并调用适当的方法。

的例子:

class Vehicle
{
public:
   void PrintType(); // Prints "Vehicle"
};
class Car: public Vehicle
{
 // overwrite PrintType to print "Car"
};

// In main
void main()
{
Vehicle *s = new Car();
s->PrintType();  // Prints "Vehicle"
// If PrintType was virtual then the type of s will be evaluated at runtime and the inherited function will be called printing "Car"
}