我正在创建一个银行程序,如果acc_type是current,那么obj应该是currentclass(从bank类派生)创建的,否则对象应该是saveclass(从bank类派生).can我这样使用?我用过但是它显示出错误的某种情况' obj'没有在范围内宣布。enter image description here
if(condition)
{
derivedclass1 obj; //first object
}
else
{
derivedclass2 obj; //second object
}
答案 0 :(得分:1)
简单的解决方案是:
baseclass *obj;
if(condition)
{
obj = new derivedclass1; //first object
}
else
{
obj = new derivedclass2; //second object
}
还有其他方法(我个人使用std::unique_ptr
),但这是最容易理解的。