重点:
1.当两个类没有共同基类。
采用函数模板:类具有相同的函数
- 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
(first); - auto se = dynamic_cast
(second); - if (iter == nullptr)
- {
- Get(se);
- }
- else
- {
- Get(iter);
- }
- return 0;
- }
2.当两个类有共同基类。
采用向下转型方式
- 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
GetBaseCmd(bool check) - {
- if (check)
- {
- return std::make_shared
(); - }
- else
- {
- return std::make_shared
(); - }
- }
-
- int main()
- {
- bool check{ false };
-
- auto base =GetBaseCmd(check);
- base->TestCmd();
- std::shared_ptr
baseCmd = std::dynamic_pointer_cast(base); - if (!baseCmd)
- {
- baseCmd= std::dynamic_pointer_cast
(base); - }
-
- if (baseCmd)
- {
- baseCmd->TestCmd();
- }
- return 0;
- }