虚函数 [英] Virtual functions

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

问题描述

我真的不明白 - 当我应该使用虚拟函数,我会很高兴,如果有人可以解释给我,谢谢

I don't really understand - when am I supposed to use virtual functions?I'll be glad if someone could explain it to me, thanks.

推荐答案

虚拟方法来多态性的关键。 。标记为虚方法可以在派生类中重写,修改或专业类的行为

Virtual methods are the key to polymorphism. A method marked as virtual can be overriden in derived classes, to alter or specialize the behavior of the class.

例如:

class Base
{
    public virtual void SayHello()
    {
        Console.WriteLine("Hello from Base");
    }
}

class Derived : Base
{
    public override void SayHello()
    {
        Console.WriteLine("Hello from Derived");
    }
}

static void Main()
{
    Base x = new Base();
    x.SayHello(); // Prints "Hello from Base"
    x = new Derived();
    x.SayHello(); // Prints "Hello from Derived"
}

请注意,您可以重新定义(不能覆盖)不是虚拟的,但在这种情况下,它不会参与多态性的方法:

Note that you can redeclare (not override) a method that is not virtual, but in that case it won't participate in polymorphism:

class Base
{
    public void SayHello() // Not virtual
    {
        Console.WriteLine("Hello from Base");
    }
}

class Derived : Base
{
    public new void SayHello() // Hides method from base class
    {
        Console.WriteLine("Hello from Derived");
    }
}

static void Main()
{
    Base x = new Base();
    x.SayHello(); // Prints "Hello from Base"
    x = new Derived();
    x.SayHello(); // Still prints "Hello from Base" because x is declared as Base
    Derived y = new Derived();
    y.SayHello(); // Prints "Hello from Derived" because y is declared as Derived
}

这篇关于虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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