基类指针指向子类对象改如何理解


public class MyBase
{
    public virtual string Meth1()
    {
        return "MyBase-Meth1";
    }
    public virtual string Meth2()
    {
        return "MyBase-Meth2";
    }
    public virtual string Meth3()
    {
        return "MyBase-Meth3";
    }
}


class MyDerived : MyBase
{
    // Overrides the virtual method Meth1 using the override keyword:
    public override string Meth1()
    {
        return "MyDerived-Meth1";
    }
    // Explicitly hide the virtual method Meth2 using the new
    // keyword:
    public new string Meth2()
    {
        return "MyDerived-Meth2";
    }
    // Because no keyword is specified in the following declaration
    // a warning will be issued to alert the programmer that
    // the method hides the inherited member MyBase.Meth3():
    public string Meth3()
    {
        return "MyDerived-Meth3";
    }

    public static void Main()
    {
        MyDerived mD = new MyDerived();
        MyBase mB = (MyBase)mD;
        System.Console.WriteLine(mB.Meth1());
        System.Console.WriteLine(mB.Meth2());
        System.Console.WriteLine(mB.Meth3());
    }
}
输出的结果如下:
MyDerived-method1
MyBase-method2
MyBase-method3
问题如下:
1:MyBase mB = (MyBase)mD;这是把一个派生类对象隐含转化基类对象 mB 是一个基类的实例对象 为什么它具有了派生类对象的性质呢?
 为什么输出的结果不是
MyBase--method1
MyBase--method2
MyBase--method3

用C++比较好说明白:
1:指针的可访问性是由指针的定义决定的,比如说用BaseClass定义的指针,可访问的范围就是BaseClass的内存区域
2:允许用一个指向基类的指针指向派生类,由于被指向的对象的内存空间大于指针的可访问空间,所以这种向上映射是安全的
3:对象在调用虚函数的时候,是调用父类的函数还是调用派生类的函数,是和对象的类型有关的.
比如说一个派生类B,其父类是A,则B的对象调用父类中被声明为VIRTUAL的函数时,被B 所OVERRIDE的函数调用的是B里的函数,而B没有OVERRIDE

的函数调用的是基类里的函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值