我们可以根据条件声明创建类的对象吗?

时间:2017-04-07 04:15:02

标签: c++

我正在创建一个银行程序,如果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
}    

1 个答案:

答案 0 :(得分:1)

简单的解决方案是:

baseclass *obj;
if(condition)
{
    obj = new derivedclass1; //first object
}
else
{
    obj = new derivedclass2; //second object
}

还有其他方法(我个人使用std::unique_ptr),但这是最容易理解的。

相关问题