类继承/覆盖的方法 [英] Class Inheritance/Method Override

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

问题描述

这是我第一次带班工作,所以请原谅我的无知。

This is my first time working with classes, so excuse my ignorance.

我有一个宠物类,是我的基类。我有两个孩子类,狗和猫。我试图做的是有猫与狗的方法说重写宠物法汪!和喵!而不是说话。然后以另一种形式我要打印信息(名称,颜色,和他们谈话)上按下一个按钮。

I have a Pet class that is my base class. I have two children classes, Dog and Cat. What I'm trying to do is have the Cat and Dog methods override the Pet method by saying "Woof!" and "Meow!" instead of speak. Then in another form I have to print the information (name, color, and them speaking) on a button press.

       class Pet
    {
        protected string name, color, food;

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public string Color
        {
            get 
            {
                return color;
            }
            set
            {
                color = value;
            }
        }
        public string Food
        {
            get
            {
                return food;
            }
            set
            {
                food = value;
            }
        }
        public void speak(string s)
        {
            s = "Speak";
            MessageBox.Show(s);
        }

        public Pet(string name, string food, string color)
        {
            //Constructor
            this.Food = food;
            this.Name = name;
            this.Color = color;
        }




    class Dog : Pet
    {

        public Dog(string name, string food, string color)
            : base(name, food, color)
        {

        }

        protected override void speak()
        {

        }

    }

}

(冷落的猫,因为它是一样的狗差不多)

(left out the cat because it's the same as dog pretty much)

我不断收到错误错误1'Lab12.Cat.speak( ):重写时,不能改变访问修饰符'公'继承成员Lab12.Pet.speak()'。

I keep getting the error "Error 1 'Lab12.Cat.speak()': cannot change access modifiers when overriding 'public' inherited member 'Lab12.Pet.speak()' "

我在做什么错了?我知道它有什么地方与保护级别做的,我一直从公众对保护或专用交换的东西,但它不是固定任何东西。帮助别人吗?

What am I doing wrong? I know it has to do with protection levels somewhere, and I keep switching things from public to protected or private, but it isn't fixing anything. Help, anybody?

推荐答案

由于说话()原本是公共的,你需要保持公开。你不能更改访问修饰符(公私营VS)。

Since Speak() was originally public, you need to keep it public. You "cannot change access modifier" (public vs private).

此外,你不能忽略非虚拟或静态方法。 重写的基方法必须是虚拟的,抽象的,或重写

Also, you cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

取读:的 http://msdn.microsoft.com/en-us/library/ebca9ah3(v = VS.100 )的.aspx

这篇关于类继承/覆盖的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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