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
的函数调用的是基类里的函数