abstract public class Pet {
protected string _name;
public Pet(string name) {
_name = name;
}
public void printName() {
Console.WriteLine("Pet name is: "+ _name);
}
// virtual public void Speak() {
// Console.WriteLine(_name + " Speak...");
// }
abstract public void Speak();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp8
{
public class Pet
{
public Pet(string name, uint age, string food)
{
_name = name;
_age = age;
_food = food;
}
protected string _name;
protected uint _age;
protected string _food;
protected string Voice;
virtual public void PrintName()
{
Console.WriteLine("Pet's name is" + _name);
Console.WriteLine("Pet's age is" + _age);
Console.WriteLine("Pet's favorit food is" + _food);
}
virtual public void PrintVoice()
{
Console.WriteLine("Pet's voice is spking");
}
}
public class Dog : Pet
{
public Dog(string name, uint age, string food) : base(name, age, food)
{
}
override public void PrintVoice()
{
Console.WriteLine(_name + "的叫声是:" + "汪汪汪");
}
}
public class Cat : Pet
{
public Cat(string name, uint age, string food) : base(name, age, food)
{
}
override public void PrintName()
{
Console.WriteLine("宠物的名字是:" + _name);
Console.WriteLine("宠物的年龄是" + _age);
Console.WriteLine("宠物最喜欢的食物是" + _food);
}
override public void PrintVoice()
{
Console.WriteLine(_name + "的叫声是:" + "喵喵喵");
}
}
class Program
{
static void Main(string[] args)
{
Pet[] pets = new Pet[] { new Dog("旺财", 7, "肉骨头"), new Cat("阿福", 3, "小鱼干") };
for (int i = 0; i < pets.GetLength(0); i++)
{
pets[i].PrintName();
}
for (int y = 0; y < pets.GetLength(0); y++)
{
pets[y].PrintVoice();
}
}
}
}
/*楼上说的没错,Name这个错误比明显,另外是基类里定义的食物哪里:
Console.WriteLine("Pet's favorit food is" + _age); _age换成__food,不过这表面上的东西检查完了,还有关键的是,获取数组长度哪里语法有误,改正完就ok了,更正如下:
for(int i=0; i<pets.GetLength(0); i++)
{ pets[i].PrintName(); }
for (int y = 0; y < pets.GetLength(0); y++)
{ pets[y].PrintVoice(); }
一定要源码吗?打一遍不就更加熟练了吗
之前的视频有说到啊,重载也很简单,说白了就是在同一个类中,有两个或者两个以上的同名函数,但是他们的参数的个数或者类型不同,我们就称这样的方法是重载。
你要想把所有派生类(比如,狗狗、猫)放到一个容器中做处理,那就得用到基类的引用
就卡了运行时的显示
public class dog:pet
{
public dog(string name): base(name)
{
代码最后加一条 : console.Read();
在Main函数里面声明的Pet,是通过一个基类的引用来调用派生类对象。此处是Pet数组,那就是一个通过基类的引用来调用派生类对象的数组
itellyou.cn
或者微软官网,不过微软官网的目前只支持X64,如果你的系统是32位的话,到itellyou.cn里面下载合适的版本,2014是个不错的选择,同时也可以选择免费版本