C++与Java比较之向上转型

两种语言在使用基础类型访问派生类方法不同机制
C++由于使用静态邦定,所以在无法识别基类型引用或指针调用重载函数方法

例如

class Instrument
{
public:
void play1()
{
cout<<"Instrument calling play1"< }
virtual void play2()
{
cout<<"Instrument calling play2"< }

};
class Piano :public Instrument
{
public:
void play1()
{
cout<<"Piano calling play1"<
}
void play2()
{
cout<<"Piano calling play2"<
}
void description()
{
cout<<"a piano is a kind of instrument"<
}
};

void main(int n,char *s[])
{
Instrument* iPointer=new Piano();
iPointer->play1();
iPointer->play2();
((Piano*)iPointer)->description();
delete iPointer;

}

运行结果:




在程序play1的方法,所以C++采用虚函数调用派生类重载基类函数,而play2方法就可以实现

在JAVA中采用动态邦定技术,所以在程序中自动识别,例如

package upcasting;

public class Upcasting
{
public static void main(String args[])
{
Instrument i = new Piano();
i.play();

//error
//i.description();
((Piano)i).description();

}
}

class Instrument
{
public void play()
{
System.out.println("Instrument calling ");
}

}
class Piano extends Instrument
{
public void play()
{
System.out.println("Piano calling");
}
public void description()
{
System.out.println("a Piano is a kind of Instrument");
}
}

没有评论: