我有一个代码,它有一个来自单个基类的派生类。当有最低要求并且当前规范发生变化时,我编写了这段代码,所以我需要创建一些100多个派生类。
我之前的实现类似于
class Base {
public:
Base();
virtual ~Base();
virtual bool isThereError() { return false;}
virtual int configureMe() { return 0; }
virtual int executeMe() { return 0;}
};
class Derived_1 : public Base {
public:
Derived_1() {
errorStatus = false;
//Some initialization code for this class }
virtual ~Derived_1() {}
bool isThereError() { return errorStatus;}
int configureMe() {
// configuration code for this class
return 0;
}
int executeMe() {
//execute the major functionality of this class based on the configuration
return 0;
}
private:
bool errorStatus;
};
class Derived_2 : public Base {
public:
Derived_2() {
errorStatus = false;
//Some initialization code for this class }
virtual ~Derived_2() {}
bool isThereError() { return errorStatus;}
int configureMe() {
// configuration code for this class
return 0;
}
int executeMe() {
//execute the major functionality of this class based on the configuration
return 0;
}
private:
bool errorStatus;
};
Main.cpp的:
#include "Base.h"
#include "Derived_1.h"
#include "Derived_2.h"
#include <set>
Derived_1 *dv1Ptr;
Derived_2 *dv2Ptr;
typedef std::set<Base *> ClassPtrList;
int main() {
ClassPtrList cpList;
dv1Ptr = new Derived_1();
dv2Ptr = new Derived_2();
dv1Ptr->configureMe();
if(dv1Ptr->isThereError()){
cpList.insert(dv1Ptr);
}
dv2Ptr->configureMe();
if(dv2Ptr->isThereError()){
cpList.insert(dv2Ptr);
}
while(true) {
for(ClassPtrList::iterator iter = cpList.begin(); iter != cpList.end(); ++iter) {
(*iter)->executeMe();
}
Sleep(1000);
}
}
我发现上面的实现会延长行数,当有更多派生类时,编写这种代码形式也不是一个好习惯。我需要使用MACRO或任何其他类型编写代码,以便每个派生类自己实例化,ClassPtrList
保留所有派生类的指针。
我开始使用像
这样的东西#define CTOR_DERIVED(drvClass) return new drvClass()
但我不确定如何避免创建更新列表的指针。我需要创建287个这样的派生类。
提前致谢。