首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多态-运动

多态-运动
EN

Stack Overflow用户
提问于 2011-07-01 12:48:51
回答 4查看 1.9K关注 0票数 1

好的,下面是练习:

定义一个名为“学生”的类,其中包含三个年级的学生。该类将具有一个计算平均成绩的函数。现在,定义一个名为student1的类,它将从学生派生出来,并添加一个函数来计算主程序grades.In的和,定义一个学生变量和student1类型的对象。执行将对象放置到变量并运行student1函数的操作。

注:这不是作业,这是我自己学的。这是代码:

代码语言:javascript
复制
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)
    {
    }
}

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-07-01 13:05:12

好吧:我想这就是他们要找的东西,尽管英国人有点乐观:

1)声明学生变量

代码语言:javascript
复制
 Student s;

2)声明Student1对象

代码语言:javascript
复制
 Student1 s1 = new Student1(1,2,3);

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

代码语言:javascript
复制
s = s1;

4)运行函数(注意,您必须将s转换为Student1类型,以访问类型特定的函数和)

代码语言:javascript
复制
Console.WriteLine(((Student1)s).Sum());
票数 1
EN

Stack Overflow用户

发布于 2011-07-01 12:52:06

具体如下所述:

代码语言:javascript
复制
// 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#的多态性。我建议您阅读该链接以查看实际使用示例。

票数 1
EN

Stack Overflow用户

发布于 2011-07-01 12:53:26

从面向对象的角度来看,我在代码中看到的主要缺陷是使Student1从Student中扩展。在使用继承时,请确保它是一个真正的扩展(是)。你最好做一个学生班,并实施和方法和平均方法。

从面向对象的角度来看,我认为以下内容就足够了。

代码语言:javascript
复制
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;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6548164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档