覆盖非虚函数和虚函数的区别是什么?
What is the difference from overwriting a nonvirtual function and a virtual?
在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"
}
相关文章:
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 这里的字符串函数是什么意思
- 这个函数是什么意思(我的英语sry)
- C++ 中的 use 函数是什么?
- C++中的编译时函数是什么?
- 使用 DnsQuery 或 getaddrinfo 的正确函数是什么?
- Lua 中看起来像表的函数是什么?
- "AfxIsValidAddress"函数的等效标准函数是什么?
- 子类的构造函数后跟冒号后的基类构造函数是什么意思?
- MFC 用于计算控件的高光、阴影等的算法或函数是什么?
- 具有多个非可选参数的转换构造函数是什么样子的?为什么它有意义
- 不确定 c++ 中的常量函数是什么
- 指针的最快散列函数是什么
- 注册用于提升io_service的每个对象的回调函数是什么?
- 在 g++ 中生成 "-L" 和 -rpath 标志的等效函数是什么
- Boost.Python中的dispatch函数和forwarding函数是什么意思
- 给定情况下的良好哈希函数是什么
- C++ 中的"导出函数"是什么意思?
- C++ std::unordered_map 中使用的默认哈希函数是什么