#include <iostream>using namespace std;class A {public: virtual voID f() { cout << "0" << endl; }}; class B : public A{public: voID f() { cout << "1" << endl; }};class C : public B{public: voID f() { cout << "2" << endl; }};int main() { A *pa = new B(); B *pb = new C(); pa->f(); pb->f();}
根据我的理解,pa-> f()执行B的f()函数,因为A是虚拟的,但是当B的f()不是虚拟时,为什么pb-> f()执行C的f()函数.
另外,如果我从A类中删除’virtual’,它会打印0 1,这是有道理的,因为A和B执行它们自己的f()函数,因为它们不是虚拟的.如果它没有受到影响,pb-> f()会如何变化,因为只有A会发生变化?
解决方法but why does pb->f() execute C’s f() function when B’s f() is not virtual.
因为pb的动态类型是C而C :: f确实是虚拟的.当你申报时
virtual voID f();
在基类中,层次结构中派生类的每个其他voID f()也是虚拟的,如§10.3/ 2所示:
If a virtual member function vf is declared in a class Base and in a class Derived,derived directly or indirectly from Base,a member function vf with the same name,parameter-type-List (8.3.5),cv-qualification,and ref- qualifIEr (or absence of same) as Base::vf is declared,then Derived::vf is also virtual (whether or not it is so declared) and it overrIDes112 Base::vf.
(强调我的)
事实上:
class A {public: virtual voID f() { cout << "0" << endl; }}; class B : public A{public: virtual voID f() { cout << "1" << endl; }};class C : public B{public: virtual voID f() { cout << "2" << endl; }};
相当于你的代码.恰好C标准允许在这些情况下省略虚拟.
总结以上是内存溢出为你收集整理的C中3个类的多态性全部内容,希望文章能够帮你解决C中3个类的多态性所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)