通过基类指针将派生类引用传递给函数 [英] Passing a Derived class reference to a function through a Base Class Pointer

查看:124
本文介绍了通过基类指针将派生类引用传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm pretty sure this is OOP 101 (maybe 102?) but I'm having some trouble understanding how to go about this.

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

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
}

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

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?

我正确执行此操作吗?还是我离开这里了?

Am I doing this correctly or am I way off base here?

推荐答案

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

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

#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()函数.这无疑为我打开了一些大门.谢谢那些帮助过的人.

Print(&player) and Print(&enemy) do call their respective DrawCard() functions as I hoped they would. This has definitely opened some doors to me. Thank you to those who helped.

这篇关于通过基类指针将派生类引用传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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