Virtual functions

后端 未结 7 1519
清酒与你
清酒与你 2020-12-11 06:39

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.

相关标签:
7条回答
  • 2020-12-11 07:35
    public abstract class Weapon
    {
        public virtual abstract FireOnTarget();
    }
    
    public class Pistol : Weapon
    {
        public override FireOnTarget()
        {
            LoadPowder();
            LoadBullet();
            CockIt();
            PullTheTrigger();
        }
    }
    
    public class SucideBomber : Weapon
    {
        public override FireOnTarget()
        {
            BuyTruck();
            LoadWithC4();
            DriveToTarget();
            ActivateDetonator();
        }
    }
    

    OK now you have two classes. The point is to refer to the virtual function without knowing what actual class is there, for example:

    public void PerformFiring(Weapon W)
    {
        // do stuff
        W.FireOnTarget();
        // do more stuff
    }
    

    This method will use whichever object you send in, derived from Weapon, and call FireOnTarget on that object. For example:

    Pistol p=new Pistol();
    PerformFiring(p);
    
    0 讨论(0)
提交回复
热议问题