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

时间:2014-03-13 19:58:53

标签: c++ oop inheritance polymorphism

我很确定这是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)函数并利用基础中的虚拟吗?

我这样做是正确的,还是我离开这里?

1 个答案:

答案 0 :(得分:0)

所以,利用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()函数。这肯定为我打开了一扇门。谢谢那些帮助过的人。