前几天看Mars老师的视频教程,里面有这样一句“一个引用能调用那些成员属性(变量和函数),取决于引用的类型;调用的方法取决于引用所指向的对象。(向上转型)”
今天在使用C++的upcast时感觉不对啊?网上搜了下原来Java和C++的向上转型的机制不同。
C++向上转型使用静态邦定,所以在无法识别类类型引用或指针调用对应类的成员函数方法。
c++示例:
- class Base
- {
- public:
- virtual void display() //虚方法,可以被子类重写
- {
- cout<<"Base display()"<<endl;
- }
- void say()
- {
- cout<<"Base say()"<<endl;
- }
- void exec()
- {
- display();
- say();
- }
- void f1(string a)
- {
- cout<<"Base f1(string)"<<endl;
- }
- void f1(int a)
- {
- cout<<"Base f1(int)"<<endl;
- } //overload
- };
- class DeriveA:public Base
- {
- public:
- void display()
- {
- cout<<"DeriveA display()"<<endl;
- } //override
- void f1(int a,int b)
- {
- cout<<"DeriveA f1(int,int)"<<endl;
- } //redefining
- void say()
- {
- cout<<"DeriveA say()"<<endl;
- } //redefining
- };
- int main()
- {
- DeriveA a;
- Base *b = &a;
- b->say();
- a.say();
- b->exec(); //display():version of DeriveA call(polymorphism) say():version of Base called(allways )
- a.exec(); //same result as last statement
- return 0;
- }
运行结果:
Base say()
DeriveA say()
DeriveA display()
Base say()
DeriveA display()
Base say()
Java示例:
JAVA中采用动态邦定技术,所以在程序中自动识别,调用的方法取决于引用所指向的对象。
- 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");
- }
- }
- public class Upcast
- {
- public static void main(String args[])
- {
- Instrument i = new Piano();
- i.play();
- //error
- //i.description();
- ((Piano)i).description();
- }
- }