在C ++中:覆盖非虚拟功能和覆盖虚拟功能有什么区别?
答案 0 :(得分:8)
使用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
),在其中查找要调用的函数的实际地址 - 在运行时,每次调用虚拟成员它。在此示例中,Foo
构造函数隐式修改Derived
的条目以指向被覆盖的函数,因此通过Foo
调用Base
无关紧要终场。
答案 1 :(得分:0)
覆盖虚函数将确保在运行时评估对象的类型并调用适当的方法。
示例:
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"
}