我是否需要为所有可能的输入参数组合提供构造函数?
Do I need to provide a constructor for all possible combinations of input parameters?
我必须写一些代码,但我不知道如何用最简单的方法来做。
在我的程序中有:
Class P
Class HP: public P
Class CP: public P
and class M
我必须写M结构将能够处理输入参数的不同组合
例如:HP hp("xxx", "yyy");
HP hp_1("xx1", "yy1");
CP cp("www", "aaa");
CP cp_1("ww1", "aa1");
M m(hp, hp1);
M m_1(hp, cp);
M m_2(cp_1, hp_1);
etc...
任何想法?我有写结构为每个组合?
嗯,从你的问题看来,类HP
和CP
有一个共同的基类P
。区分HP
和CP
,完全取决于M
到底需要什么。如果M
可以使用P
的接口,那么可以使用
M
提供一个(单个)构造函数。 class M {
public:
M(P& a, P& b) {
// Do whatever you didn't specify in your question
}
// Or pointer references if preferred
M(P* a, P* b) {
// Do whatever you didn't specify in your question
}
};
即使您需要区分HP
和CP
,您仍然可以在构造函数成员初始化列表或主体中使用dynamic_cast<>
(对于上述两种变体)。
相关文章:
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 模板元编程:如何将参数包组合成新的参数包
- 组合函数参数包和默认参数
- uncrustify:如何将多行 C 函数调用的参数组合到一行上?
- 如何在C++中找到可变参数类型表的所有组合
- 从组合类公开模板参数的替代方法
- 使用参数包在C++中组合 lambda 函数
- 将约束组合应用于参数包
- 组合类模板默认参数和变异参数
- 如何将多个可变参数模板元组类组合成一个类?
- 使用参数组合创建对象
- 组合模板参数形成函数签名时无效的 void 参数
- 在类组合中调用参数化构造函数
- 模板参数的组合排序
- C++组合参数模板元编程
- Boost.Parameter:与 CRTP 组合的命名模板参数
- 具有可变参数模板的功能组合
- 根据 qt 组合框更改参数
- 在重载函数的函数参数中使用右值引用会创建太多组合
- 传递参数递归 C++(电话号码的字母组合)