简体   繁体   English

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

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

I'm pretty sure this is OOP 101 (maybe 102?) but I'm having some trouble understanding how to go about this. 我很确定这是OOP 101(也许是102?),但是我在理解如何进行此操作时遇到了一些麻烦。

I'm trying to use one function in my project to produce different results based on what objet is passed to it. 我试图在项目中使用一个函数,根据传递给对象的东西产生不同的结果。 From what I've read today I believe I have the answer but I'm hoping someone here could sure me up a little. 从我今天所读的书中,我相信我已经找到了答案,但是我希望这里的人可以肯定我。

//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
}

With this, if I have multiple classes derived from the Base will I be able to pass any Derived class to the DoStuff(A *ref) function and utilize the virtuals from the base? 有了这个,如果我有多个从Base派生的类,我是否可以将任何Derived类传递给DoStuff(A *ref)函数,并利用来自Base的虚函数?

Am I doing this correctly or am I way off base here? 我是在正确执行此操作,还是要离开这里?

So, utilizing IDEOne which was shared with me by Maxim (Thank you very much), I was able to confirm that I was doing this correctly 因此,利用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) and Print(&enemy) do call their respective DrawCard() functions as I hoped they would. 正如我希望的那样, Print(&player)Print(&enemy)确实调用了它们各自的DrawCard()函数。 This has definitely opened some doors to me. 这无疑为我打开了一些大门。 Thank you to those who helped. 感谢您的帮助。

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

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