我想做的是这样的:
void SomeFunction(Base *){//do something}
void SomeFunction(Derived *){//do something else}
这在 C++ 中可能吗?到目前为止,我的尝试只是调用该函数的基本版本。为了清楚起见,这是一个示例。
例子:
#include <iostream>
#include <vector>
class Base
{
public:
Base () {std::cout << "Base Constructor for " << this << std::endl;}
void virtual PrintSomething ()
{
std::cout << "I am Base!" << std::endl;
};
};
class Derived : public Base
{
public:
Derived () : Base () {std::cout << "Derived Construtor for " << this << std::endl;}
void virtual PrintSomething ()
{
std::cout << "I am Derived!" << std::endl;
};
};
void DoAmazingStuff ( Base * ) {std::cout << "Amazing!" << std::endl;}
void DoAmazingStuff ( Derived * ) {std::cout << "DERP!" << std::endl;}
int main ()
{
std::vector<Base *> some_vector;
Base *x = new Base ();
Derived *y = new Derived ();
some_vector.push_back ( x );
some_vector.push_back ( y );
// This is the part that isn't functioning as expected.
/******************************************/
DoAmazingStuff ( some_vector[0] );
DoAmazingStuff ( some_vector[1] );
/******************************************/
std::cin.get ();
std::cin.get ();
delete some_vector[0];
delete some_vector[1];
}
永远不会调用以下行:
void DoAmazingStuff ( Derived * ) {std::cout << "DERP!" << std::endl;}