2014-03-13 24 views
0

我很確定這是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 
} 

藉助於此,如果我已經從鹼衍生多個類我將能夠任何派生類從基部傳遞到DoStuff(A *ref)功能和利用虛函數?

我是否正確地做了這件事,還是我在這裏基地?

+0

你爲什麼不運行代碼,看看你能得到什麼? – taocp

+0

@taocp很想去,但我在夜裏工作。奇怪的是,我在沒有IDE的情況下完成了大部分編程。 – Prototype958

+0

我建議你首先看一下C++中的虛函數和繼承。您當前的代碼中存在一些錯誤。 – taocp

回答

0

因此,利用這是由馬克西姆(非常感謝你)與我分享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()功能我希望他們會。這無疑給我打開了一些門。感謝那些幫助過的人。