继承类,base的问题!

ekeen 2003-07-20 09:38:59
class Vehicle
{
public int wheels;
protected float weight ;
public Vehicle(int w, float g)
{
wheels = w;
weight = g;
}
public void speak()
{
Console.WriteLine("the w Vehicle is speaking!");
Console.WriteLine("Vehicle {0},{1}",wheels,weight);
}
}
class car:Vehicle
{
int passengers;
public car(int w,float g,int p):base(w,g)
//为什么要加:base(w,g),不加的话就报重载“Vehicle”方法未获取“0”参数的错

{
wheels = w;
weight = g;
passengers = p;

}
new public void speak()
{
Console.WriteLine("car {0},{1},{2}",wheels,weight,passengers);
Console.WriteLine("the car is speaking :di-di----!");
}
}
...全文
85 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
soaringeagle 2003-10-12
  • 打赏
  • 举报
回复
----------------
TheAres(班门斧)
也就是:
public car(int w,float g,int p)
等于
public car(int w,float g,int p):base()
显然父类没有这个构造函数。
---------------
太奇怪,实在想不通为什么要有这样的继承机制。难道没办法的么?
我现在习惯把空参数的构造函数定义为空的了。吐血。
lufly2000 2003-07-20
  • 打赏
  • 举报
回复
斑竹说的对!

如果你的基类有一个无参数的构造函数则不加base(w,g)就不会有任何问题
TheAres 2003-07-20
  • 打赏
  • 举报
回复
public car(int w,float g,int p)会调用父类的构造函数。如果你什么也不指定,则相当于调用没有任何参数的父类构造函数。

也就是:
public car(int w,float g,int p)
等于
public car(int w,float g,int p):base()
显然父类没有这个构造函数。



public car(int w,float g,int p):base(w,g)
就是要显式调用父类的构造函数public Vehicle(int w, float g) ,所以就没有问题。


110,537

社区成员

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

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

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