菜鸟求助C#问题

vampire_ud 2006-12-27 11:22:54
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{



public class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;

}
public class Point3D : Point
{
public int z;
public Point3D(int x, int y, int z)
: base(x, y)
{
this.z = z;
}
}




static void Main(string[] args)
{
Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);


Console.WriteLine("A:{0}\nB:{1}\n", a.x, b.y);
Console.WriteLine("Z:{0}", b.z);





}
}
}
一个类继承它的基类的成员 继承意味着一个类隐式地包含其基类的所有成员,但基类的构造函数除外。派生类能够在继承基类的基础上添加新的成员,但是它不能移除继承成员的定义。 ,Point3D 类从 Point 类继承了 x 字段和 y 字段,每个 Point3D 实例都包含三个字段 x、y 和 z。
从某个类类型到它的任何基类类型存在隐式的转换。 类类型的变量可以引用该类的实例或任何派生类的实例。例如,对于前面给定的类声明,Point 类型的变量既可以引用 Point 也可以引用 Point3D:
Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);
为什么不能输出b.z?????
...全文
128 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
colaxu 2006-12-27
  • 打赏
  • 举报
回复
Point 基类是没有z的.
liujia_0421 2006-12-27
  • 打赏
  • 举报
回复
其实道理很简单..

我们知道所有类都是从Object继承而来的..

我们可以将任何类型赋给一个object对象:
student std=new student("test");
object obj=std;

比如说student有一个Name属性..

你能直接用obj.Name吗?

不行吧..

还是等转一下:
((student)obj).Name="yourName";
liujia_0421 2006-12-27
  • 打赏
  • 举报
回复
或者这样:

Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);


Console.WriteLine("A:{0}\nB:{1}\n", a.x, b.y);
Console.WriteLine("Z:{0}", ((Point3D)b).z);
liujia_0421 2006-12-27
  • 打赏
  • 举报
回复
try..

Point3D b = new Point3D(10, 20, 30);

Point 不包含z字段啊..
北京的雾霾天 2006-12-27
  • 打赏
  • 举报
回复
Point b = new Point3D(10, 20, 30);
执行这个语句后b实际上确实是Point3D的变量,但是确进行了向Point的转换,而Point是没有z的,所以你在b上看不到z这个属性.
vampire_ud 2006-12-27
  • 打赏
  • 举报
回复
谢谢!

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧