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

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

有什么想法吗? 我是否为每个组合编写了结构?

嗯,从你的问题看来,classes HPCP 有一个共同的基础 class P。这完全取决于 M 通过区分 HPCP 实际需要什么。如果 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<>(对于提到的两种变体)。