基类转换成派生类的问题
class Program
{
static void Main(string[] args)
{
A a = new A();
B b =new B();
b.a = 300;
b.b = 20;
B e = a.Clone() as B;//这里会运行错误 但是变成b.clone() as B 就会正常
System.Console.WriteLine(e.a);
}
}
public class A : ICloneable
{
public A()
{
}
public int a=200;
#region ICloneable 成员
public virtual object Clone()
{
return MemberwiseClone();
}
#endregion
}
public class B:A
{
public int b = 10;
public B():base()
{
}
public override object Clone()
{
B c= base.Clone() as B;//为什么这里可以把基类变成派生类?????????
c.b = 100;
return c;
}
}
{
static void Main(string[] args)
{
A a = new A();
B b =new B();
b.a = 300;
b.b = 20;
B e = a.Clone() as B;//这里会运行错误 但是变成b.clone() as B 就会正常
System.Console.WriteLine(e.a);
}
}
public class A : ICloneable
{
public A()
{
}
public int a=200;
#region ICloneable 成员
public virtual object Clone()
{
return MemberwiseClone();
}
#endregion
}
public class B:A
{
public int b = 10;
public B():base()
{
}
public override object Clone()
{
B c= base.Clone() as B;//为什么这里可以把基类变成派生类?????????
c.b = 100;
return c;
}
}
...全文
相关推荐
详解C++中基类与派生类的转换以及虚基类
这种情况下,派生类对象会自动转换成基类类型,但函数只能访问基类的部分。4. **指针转换**:派生类对象的地址可以赋给指向基类对象的指针。
c++期末选择填空复习题
公有继承意味着基类的公有和保护成员在派生类中保持原有的访问性,而私有继承则使基类的公有和保护成员在派生类中变为私有。派生类可以看作是基类定义的延续,它可以提供更具体的功能或增加新的特性。
C++重点复习题(多态和继承).doc
内联函数解决频繁调用的问题。十、函数模板定义函数模板定义中,返回类型错误的定义会导致函数调用错误。
金山笔试题金山笔试题:涉及C++...及一些算法设计技术.....
继承关系问题:A为基类,B是A的保护派生类,C是B的私有派生类,D是C的公有派生类。
C++笔记:派生类到基类转换到可访问性
要确定到基类的转换是否可访问,可以考虑基类的public成员是否可访问,如果可以,转换是可以访问的,否则,转换是不可访问的。


