c++和java中关于如何调用父类方法和子类方法的辨析
首先观察下面两个程序(分别使用vc6.0和myecllipse10测试)
class A{void f(){System.out.println("class A");}}class B extends A{void f(){System.out.println("class B");}}public class Test {public static void main(String[] args) {A p = null;p = new A();p.f();//class Ap = new B();p.f();//class B//B b = (B) new A();//Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B}}以上两个程序都有一个父类A,以及子类B,两个类中都有f()方法。
可以发现在c++中,函数调用是根据函数前面指针的类型决定的(p的类型),java是根据p所指的对象的类型(p = new ?())来决定的。
以后写c++中,如果父类指针要调用子类方法,切记要进行强制类型转换。