gpt4 book ai didi

c# - 多态性——练习

转载 作者:太空宇宙 更新时间:2023-11-03 22:11:15 27 4
gpt4 key购买 nike

好吧,这就是练习:

Define a class named student, containing three grades of students. The class will have a function that calculates the grades average. Now, define a class named student1 which will be derived from student and will add a function to calculate the sum of the grades.In the Main program, define a student variable and object of type student1. Perform placement of the object to variable and run the function of 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)
{
}
}

我真的不知道在主课上该做什么,我该如何进行这个布置,而且,我想知道这样做有什么好处,如果到目前为止我有错误,请告诉我,非常感谢。

最佳答案

好的:我想这就是他们要找的东西,尽管英语有点生硬:

1) 声明学生变量

 Student s;

2) 声明Student1对象

 Student1 s1 = new Student1(1,2,3);

3) 执行对象到变量的放置:

s = s1;

4) 运行该函数(请注意,您必须将 s 转换为 Student1 类型才能访问类型特定的函数 Sum)

Console.WriteLine(((Student1)s).Sum());

关于c# - 多态性——练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com