我是否需要为所有可能的输入参数组合提供构造函数?

Do I need to provide a constructor for all possible combinations of input parameters?

本文关键字:组合 参数 构造函数 输入 是否 有可能      更新时间:2023-10-16

我必须写一些代码,但我不知道如何用最简单的方法来做。

在我的程序中有:

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...

任何想法?我有写结构为每个组合?

嗯,从你的问题看来,类HPCP有一个共同的基类P。区分HPCP,完全取决于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
     }
 };

即使您需要区分HPCP,您仍然可以在构造函数成员初始化列表或主体中使用dynamic_cast<>(对于上述两种变体)。