问题
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
}
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?
回答1:
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)
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.
来源:https://stackoverflow.com/questions/22389580/passing-a-derived-class-reference-to-a-function-through-a-base-class-pointer