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)
功能和利用虛函數?
我是否正確地做了這件事,還是我在這裏基地?
你爲什麼不運行代碼,看看你能得到什麼? – taocp
@taocp很想去,但我在夜裏工作。奇怪的是,我在沒有IDE的情況下完成了大部分編程。 – Prototype958
我建議你首先看一下C++中的虛函數和繼承。您當前的代碼中存在一些錯誤。 – taocp