本文主要是介绍变量承接函数类型的方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
重点:
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<FirstCmd*>(first);auto se = dynamic_cast<SecondCmd*>(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<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;
}
这篇关于变量承接函数类型的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!