这是我写的:
...
#define JOIN(x,y) x##y
class A
{
public:
A(){};
virtual ~A(){};
}
class AA : public A
{
public:
AA(){};
virtual ~AA(){};
}
class AB : public A
{
public:
AB(){};
virtual ~AB(){};
}
int main()
{
for(int i = 0; i < 2; ++i)
{
A *a = NULL;
if(i == 0)
a = new JOIN(A,A);
else
a = new JOIN(A,B);
delete a;
a = NULL;
}
return 0;
}
如果有AC,AD,...,AZ类,那么有很多if ... else ...和JOINs
如何减少if ... else ...的数量......看起来更舒服!
答案 0 :(得分:0)
如果要分解代码,可以使用模板:
template <typename T>
void foo()
{
A* a = new T;
// ...
delete a;
}
甚至
template <typename T>
void foo()
{
T a;
// ...
}
然后
int main()
{
foo<AA>();
foo<AB>();
foo<AC>();
foo<AD>();
foo<AE>();
}