【发布时间】:2017-01-01 19:09:19
【问题描述】:
假设我有一些 C++ 抽象类,它所有的继承类都有不同的构造函数:
class Abstract{
//don't worry, there is some pure virtual method here
}
class A : public Abstract {
public:
A (int Afirst, std::string Asecond, int Athird) {...}
...
}
class B : public Abstract {
public
B (double Bfirst, std::int Bsecond) {...}
...
}
class C : public Abstract {
public
C (std::string Cfirst, double Csecond, int Cthird, float Cfourth) {...}
}
如您所见,所有继承的类都有(可能)不同的构造函数。
现在,我想写一个通用的main(),类似于:
int main (int argc, char *argv[]){
if(argc < 2){
std::cerr<<"Too few arguments!"<<std::endl;
exit(1);
}
std::string type = argv[1];
Abstract *abs;
if(!type.compare("A"){
if(argc < 5){
std::cerr<<"Too few arguments for A!"<<std::endl;
exit(1);
}
abs = new A(atoi(argv[2]), argv[3], argv[4]);
}
//similar for B, C, D
}
我想知道是否有最好的方法来做到这一点,例如直接将char *argv[] 传递给每个构造函数并在构造函数内部进行所有检查(并最终如here 所述抛出异常)。
【问题讨论】:
-
您将无法避免检查参数是否与给定的构造函数相匹配,但我不会用检查代码污染类。我会编写一个工厂函数,它采用
argc和argv并返回适当类的实例。这样可以保留检查代码。
标签: c++ constructor abstract-class