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

前几天看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();
    }
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值