对继承的怀疑,请解释 [英] doubt for inheritance please explain

查看:55
本文介绍了对继承的怀疑,请解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

hello all,

Class a{}
Class b:clsss a()
{}
Class c:class b()
{}


那你能解释一下吗?


So can you explain

C objc=new a()


感谢all


Thanks to all

推荐答案

派生类可以转换为基类,否则不能转换.
您的说法有误.
可以是a obj=new c()
Derived class can be converted to Base class, not otherwise.
Your statement is wrong.
It can be a obj=new c()


将您的示例排序,以便将其编译为:
Sorting your example out so it would compile gives:
class A
  {
  }
class B : A
  {
  }
class C : B
  {
  }
...
  C objc = new A();

仍将无法编译:您将收到错误无法隐式转换类型''MyClass.A "到"MyClass.C".存在显式转换(您是否缺少演员表?)"
因为C是从B派生的,而B是从A派生的,所以类型C的每个项目都包含类型B的项目要做的所有事情,而类别B则包含类A所做的一切.这意味着类B的项可以包含类B 的实例或从类b 派生的任何对象.它不能保存类A的实例,因为类A对创建类B所做的任何附加操作一无所知.如果编译器允许您将calss A的实例设置为类C的引用变量,则程序将在运行时失败尝试使用任何C类功能的时间,因为该变量所引用的对象不包含这些功能.

这有点像说:一本教科书(B类)是一本书的类型(A类),而一本物理教科书(C类)是一种教科书(B类),所以如果我购买一本书(一类, A),那么它将包含有关物理的信​​息,而不是诗歌."

It will still not compile: you will get an error "Cannot implicitly convert type ''MyClass.A'' to ''MyClass.C''. An explicit conversion exists (are you missing a cast?)"
Because C is derived from B, and B is derived from A, each item of type C contains everything that an item of type B does, and B contains everything that class A does. What that means is that an item of class B can hold an instance of Class B or anything derived from class b. It cannot hold an instance of class A, because class A does not know anything about any additions made to create class B. If the compiler allowed you to set an instance of calss A into a class C reference variable, your program would fail at run time when you tried to use any of the class C features, because the object that the variable was referring to did not contain them.

It''s a bit like saying "A textbook (class B) is a type of book (class A), and a Physics textbook (class C) is a type of textbook (class B), so if I buy a book (class A), then it will contain information on Physics, rather than poetry"


C objc=new a()
该代码不符合要求.

由于继承层次结构,类A是C的父级-C是B的子级,B是A的子级.
因此A objC = new C();将完全没有问题.

以这种方式考虑,子类可以提供比基类更多的功能,因此您可以轻松地将派生对象类型转换为基类,而反之则不行.
C objc=new a()
This code will not complile.

Class A is the parent of C due to inheritance hierarchy - C is a child of B and B is a child of A.
Thus A objC = new C(); will complile without any issues.

Think of it this way, subclasses can provide more than base classes, so you can easily typecast a derived object into the base class but not the other way round.


这篇关于对继承的怀疑,请解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆