簡體   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