在C++中:覆盖非虚函数和覆盖虚函数有什么区别?覆盖非虚拟功能和虚拟功能有什么区别?
3
A
回答
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
指针被调用并不重要。
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"
}
相关问题
- 1. 儿童班的虚拟和非虚拟功能的区别
- 2. 虚拟功能与纯虚拟功能的区别?
- 3. 覆盖和隐藏虚拟功能
- 4. 虚拟功能常量vs虚拟功能非常量
- 5. 虚拟功能
- 6. 为什么虚拟功能会隐藏?
- 7. 为什么使用虚拟功能?
- 8. 非虚拟接口 - 如何调用正确的虚拟功能
- 9. 方法覆盖和功能覆盖/超载有什么区别
- 10. 并行和虚拟有什么区别
- 11. 抽象和虚拟有什么区别?
- 12. 虚拟功能问题
- 13. 虚拟功能与回调
- 14. 虚拟功能输出?
- 15. 虚拟功能错误?
- 16. 功能为虚拟变量
- 17. 虚拟功能故障
- 18. 要求父虚拟功能
- 19. 优势虚拟功能
- 20. 虚拟功能的超载
- 21. 为什么这些模板化功能不像虚拟功能?
- 22. 具有虚拟功能的类中的非虚函数
- 23. 为什么虚拟表只有在虚拟功能的情况下才需要?
- 24. 虚拟,覆盖,新和密封覆盖之间的区别
- 25. 使用虚拟功能和重新定义之间的区别
- 26. 带空虚的虚拟方法和纯虚拟方法有什么区别?
- 27. 用更多参数覆盖虚拟功能
- 28. C++虚拟功能重写和重载
- 29. 虚拟功能不能正常工作
- 30. 单个虚拟桌面如何跟踪新的虚拟功能?
改写装置无关。你想问关于成员函数隐藏,覆盖或重载吗?如果你想澄清你的问题,在这里搜索每一个。 – 2011-05-03 17:40:00
如果没有人提及它:请参考[The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)并给自己买一个关于C++的好书。 – 2011-05-03 17:42:00