C++ 覆盖非虚拟函数和虚拟函数有什么区别?
在C++中:重写非虚拟函数和重写虚拟函数有什么区别C++ 覆盖非虚拟函数和虚拟函数有什么区别?,c++,inheritance,virtual-functions,C++,Inheritance,Virtual Functions,在C++中:重写非虚拟函数和重写虚拟函数有什么区别 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()
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"
// 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
的条目由派生的
构造函数隐式修改,以指向被重写的函数,因此通过基
指针调用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"
}
覆盖没有任何意义。是否要询问成员函数隐藏、重写或重载?如果你想澄清你的问题,请在这里搜索每一个。如果没有人提到它:请咨询并购买一本关于C++的好书。