在OOP中继承苦力 [英] Struggling with inheritance in OOP

查看:77
本文介绍了在OOP中继承苦力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些OOP练习,但我似乎不明白。这是我的父母班:

I am trying to do some practice of OOP but I seem to not understand something. Here is my parents class:

class Human
    {
        public string name;
        public int age;

        public Human(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public string Name
        {
            get { return name; }
            set { this.name = value; }
        }
        public int Age
        {
            get { return age; }
            set { this.age = value; }
        }





这是我的孩子班:



And here is my child class :

class Student:Human
    {
        private string speciality;
        private int facultynumber;

        public Student(string speciality, int facultynumber)
            : base(name,age)
        {
            this.facultynumber = facultynumber;
            this.speciality = speciality;
        }

        public string Speciality
        {
            get { return speciality; }
            set { this.speciality = value;}
        }
        public int Facultynumber
        {
            get { return facultynumber; }
            set { this.facultynumber = value; }
        }





为什么它会在基础上触发错误:访问非静态时需要对象引用会员



我尝试了什么:



我真的不喜欢知道该做什么...



Why is it firing me an Error, on the base : object reference is required to access non-static member

What I have tried:

I really don't know what to do...

推荐答案

你应该将所有参数传递给学生:



You should be passing all the parameters to the Student:

public Student(string name, int age, string speciality, int facultynumber)
            : base(name,age)
        {
            this.facultynumber = facultynumber;
            this.speciality = speciality;
        }





另外,请考虑将人类中的名称/年龄字段设为受保护或私有。



Also, consider making the name/age fields in the human class protected or private.


你好,

你不能这样做。它可以是

Hello ,
you cannot do this . It can be
public Student(string name, int age, string speciality, int facultynumber)
            : base("SomeName",10)





它可以是


or
it can be

public Student(string speciality, int facultynumber)
              : base(speciality, facultynumber)



谢谢


Thanks


这是有问题的代码



this is the problematic code

public Student(string speciality, int facultynumber)
    : base(name,age)
{
    this.facultynumber = facultynumber;
    this.speciality = speciality;
}







因为你试图将父类变量作为参数传递给构造函数父类。



尝试使用,测试硬编码值而不是它应该工作(例如test,1)




because you are trying to pass parent class variables as parameter in the constructor of parent class.

Try using, test hard coded values than it should work (for e.g "test" ,1)


这篇关于在OOP中继承苦力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆