现在的位置: 首页 > 综合 > 正文

c++和java中关于如何调用父类方法和子类方法的辨析

2018年03月20日 ⁄ 综合 ⁄ 共 770字 ⁄ 字号 评论关闭

首先观察下面两个程序(分别使用vc6.0和myecllipse10测试)

#include <iostream>
using namespace std;

class A
{
public:
	
	void f()
	{
		cout<<"class A "<<endl;
	}

};

class B : public A
{
public:

	void f()
	{
		cout<<"class B "<<endl;
	}
};

void main()
{
	A* p;
	p = new A();
	p->f();//class A

	p = new B();
	p->f();//class A

	p = new B();
	((B*)p)->f();//class B


	B* b;
	//b = new A();//compile error


}

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 A
		
		p = 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++中,如果父类指针要调用子类方法,切记要进行强制类型转换。


一起学习,一起进步,欢迎访问我的博客:http://blog.csdn.net/wanghao109

抱歉!评论已关闭.