我在 C++ 中有以下 switch 语句,其中 BaseType 是一个抽象类:
switch (foo)
{
case 1:
{
DerivedType t = SomeDerivedType(); //Instantiate some derived type.
FunctionThatTakesBaseType(t); //Pass it to this function.
break;
}
case 2:
{
SomeOtherDerivedType t = SomeOtherDerivedType(); //Instantiate some other dervied type.
FunctionThatTakesBaseType(t) //Pass it to the same function.
break;
}
case 3:
{
...
}
}
如果这是 C#,我会通过在 switch 语句之外声明一个基类型变量,在 switch 中定义它,并在 switch 之后调用该函数一次来更简洁地编写,如下所示:
BaseType t; //Declared outside of scope of the switch so I can call the function once afterward.
switch (foo)
{
case 1:
t = SomeDerivedType();
break;
case 2:
t = SomeOtherDerivedType();
break;
case 3:
...
}
FunctionThatTakesBaseType(t);
有没有办法在 C++ 中做到这一点?如何在外部作用域中声明抽象类型变量并在内部作用域中使用具体类型定义它?有没有一种方法可以像编写 C# 代码一样简洁地编写 C++ 代码?你不能这样做:
Base t; //ERROR: In C++ this attempts to instantiate the abstract base class!
看来你不能这样做:
Base* t; //OK, but to assign the variable inside the switch do you have to allocate the
//object on the heap?
是的,你必须使用指针和堆分配。
BaseType *t;
switch (foo)
{
case 1:
t = new SomeDerivedType();
break;
case 2:
t = new SomeOtherDerivedType();
break;
case 3:
...
}
您也可以考虑使用智能指针。例如
std::unique_ptr<BaseType> t;
switch (foo)
{
case 1:
t = std::make_unique<SomeDerivedType>();
break;
case 2:
t = std::make_unique<SomeOtherDerivedType>();
break;
case 3:
...
}
这正是所有对象都在堆上分配的语言中所发生的情况。