重点:
1.当两个类没有共同基类。
采用函数模板:类具有相同的函数
cpp
class FirstCmd
{
public:
FirstCmd()=default;
~FirstCmd() = default;
void TestCmd() { std::cout << 10 << std::endl;};
};
class SecondCmd
{
public:
SecondCmd() = default;
~SecondCmd() = default;
void TestCmd() { std::cout << 20 << std::endl; };
};
template<class T>
void Get(T* a)
{
a->TestCmd();
}
int main()
{
int a = 3;
int b = a * a * a-a;
FirstCmd* first=new FirstCmd();
SecondCmd* second =new SecondCmd();
auto iter = dynamic_cast<FirstCmd*>(first);
auto se = dynamic_cast<SecondCmd*>(second);
if (iter == nullptr)
{
Get(se);
}
else
{
Get(iter);
}
return 0;
}
2.当两个类有共同基类。
采用向下转型方式
cpp
class BaseCmd
{
public:
BaseCmd() = default;
~BaseCmd() = default;
virtual void TestCmd() = 0;
};
class FirstCmd:public BaseCmd
{
public:
FirstCmd()=default;
~FirstCmd() = default;
virtual void TestCmd() { std::cout << 10 << std::endl;};
};
class SecondCmd :public BaseCmd
{
public:
SecondCmd() = default;
~SecondCmd() = default;
virtual void TestCmd() { std::cout << 20 << std::endl; };
};
std::shared_ptr<BaseCmd> GetBaseCmd(bool check)
{
if (check)
{
return std::make_shared<FirstCmd>();
}
else
{
return std::make_shared<SecondCmd>();
}
}
int main()
{
bool check{ false };
auto base =GetBaseCmd(check);
base->TestCmd();
std::shared_ptr<BaseCmd> baseCmd = std::dynamic_pointer_cast<FirstCmd>(base);
if (!baseCmd)
{
baseCmd= std::dynamic_pointer_cast<SecondCmd>(base);
}
if (baseCmd)
{
baseCmd->TestCmd();
}
return 0;
}