C++中的虚函数和虚函数表(2)

4.我们再来看看继承中虚函数的内存结构,先看下面的例子 class A { public: virtual void f() { } }; class B { public: virtual void f() { } }; class C { public: virtual void f() { } }; class Drive : public A, public B, public C { }; int main() { Drive d; cout << "Size is = " << sizeof(d) << endl; return 0; }结果如下:Size is = 12 ,相信大家一看下面的结构图就会很清楚,


图三

5.我们再来看看用虚函数实现多态性,先看个例子: class A { public: virtual void f() { cout << "A::f" << endl; } }; class B :public A{ public: virtual void f() { cout << "B::f" << endl;} }; class C :public A { public: virtual void f() { cout << "C::f" << endl;} }; class Drive : public C { public: virtual void f() { cout << "D::f" << endl;} }; int main(int argc, char* argv[]) { A a; B b; C c; Drive d; a.f(); b.f(); c.f(); d.f(); return 0; } 结果:A::f B::f C::f D::f不用解释,相信大家一看就明白什么道理!注意:多态不是函数重载

linux

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwsjdx.html