繁体   English   中英

通过基类指针将派生类引用传递给函数

[英]Passing a Derived class reference to a function through a Base Class Pointer

我很确定这是OOP 101(也许是102?),但是我在理解如何进行此操作时遇到了一些麻烦。

我试图在项目中使用一个函数,根据传递给对象的东西产生不同的结果。 从我今天所读的书中,我相信我已经找到了答案,但是我希望这里的人可以肯定我。

//Base Class "A"
class A
{
    virtual void DoThis() = 0; //derived classes have their own version
};

//Derived Class "B"
class B : public A
{
    void DoThis() //Meant to perform differently based on which
                  //derived class it comes from
};

void DoStuff(A *ref) //in game function that calls the DoThis function of
{ref->DoThis();}     //which even object is passed to it.
                     //Should be a reference to the base class

int main()
{
    B b;

    DoStuff(&b);     //passing a reference to a derived class to call
                     //b's DoThis function
}

有了这个,如果我有多个从Base派生的类,我是否可以将任何Derived类传递给DoStuff(A *ref)函数,并利用来自Base的虚函数?

我是在正确执行此操作,还是要离开这里?

因此,利用Maxim与我共享的IDEOne(非常感谢),我可以确认自己做得正确

#include <iostream>
using namespace std;

class Character 
{
public:
    virtual void DrawCard() = 0;    
};

class Player: public Character
{
public:
    void DrawCard(){cout<<"Hello"<<endl;}
};

class Enemy: public Character
{
public:
    void DrawCard(){cout<<"World"<<endl;}
};

void Print(Character *ref){
    ref->DrawCard();
}

int main() {

    Player player;
    Enemy enemy;

    Print(&player);

    return 0;
}

正如我希望的那样, Print(&player)Print(&enemy)确实调用了它们各自的DrawCard()函数。 这无疑为我打开了一些大门。 感谢您的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM