好的,下面是练习:
定义一个名为“学生”的类,其中包含三个年级的学生。该类将具有一个计算平均成绩的函数。现在,定义一个名为student1的类,它将从学生派生出来,并添加一个函数来计算主程序grades.In的和,定义一个学生变量和student1类型的对象。执行将对象放置到变量并运行student1函数的操作。
注:这不是作业,这是我自己学的。这是代码:
class Student
{
protected int grade1, grade2, grade3;
public Student(int grade1, int grade2, int grade3)
{
this.grade1 = grade1;
this.grade2 = grade2;
this.grade3 = grade3;
}
public double Average()
{
return (grade1 + grade2 + grade3) / 3;
}
}
class Student1 : Student
{
public Student1(int grade1, int grade2, int grade3)
: base(grade1, grade2, grade3)
{
}
public double Sum()
{
return grade1 + grade2 + grade3;
}
}
class Program
{
static void Main(string[] args)
{
}
}我真的不知道在主修课上该怎么做,我怎么做这个位置,我也想知道这样做有什么好处,如果到目前为止我有错误请告诉我,非常感谢。
发布于 2011-07-01 13:05:12
好吧:我想这就是他们要找的东西,尽管英国人有点乐观:
1)声明学生变量
Student s;2)声明Student1对象
Student1 s1 = new Student1(1,2,3);3)执行对象到变量的放置:
s = s1;4)运行函数(注意,您必须将s转换为Student1类型,以访问类型特定的函数和)
Console.WriteLine(((Student1)s).Sum());发布于 2011-07-01 12:52:06
具体如下所述:
// Define a student variable.
Student s;
// And object of type Student1.
Student1 s1 = new Student1(10, 5, 8);
// Perform placement of the object to variable.
s = s1;
// And run the function of Student1.
// But it makes no sense...
s1.Sum();
// Maybe the exercise wants it:
((Student1)s).Sum();
// Which makes no sense too, since is making an idiot cast.
// But for learning purposes, ok.嗯,我不认为这个练习是在利用C#的多态性。我建议您阅读该链接以查看实际使用示例。
发布于 2011-07-01 12:53:26
从面向对象的角度来看,我在代码中看到的主要缺陷是使Student1从Student中扩展。在使用继承时,请确保它是一个真正的扩展(是)。你最好做一个学生班,并实施和方法和平均方法。
从面向对象的角度来看,我认为以下内容就足够了。
class Student
{
protected int grade1, grade2, grade3;
public Student(int grade1, int grade2, int grade3)
{
this.grade1 = grade1;
this.grade2 = grade2;
this.grade3 = grade3;
}
public double Average()
{
return (grade1 + grade2 + grade3) / 3;
}
public double Sum()
{
return grade1 + grade2 + grade3;
}
}https://stackoverflow.com/questions/6548164
复制相似问题