c++ - 我们可以根据条件语句创建类的对象吗?

标签 c++

我正在创建一个银行程序,如果 acc_type 是当前的,那么 obj 应该由 currentclass(派生自 bank 类)创建,否则对象应该由 savingclass(派生自 bank 类)创建。我可以这样使用吗?我用过它但它显示错误 somelike 'obj' was not declared in the scope. enter image description here

if(condition)
{
    derivedclass1 obj; //first object
}
else
{
    derivedclass2 obj; //second object
}    

最佳答案

简单的解决方案是:

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

还有其他方法可以做到这一点(我个人会使用 std::unique_ptr ),但这是最容易理解的。

关于c++ - 我们可以根据条件语句创建类的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43269522/

相关文章:

c++ - 如何对此应用重载运算符?

c++ - 在 Visual Studio 中使用 decltype 派生的返回类型专门化模板

c++ - 如何克隆包含指针的对象?

c++ - 无法创建我自己的日期类

c++ - 无法弄清楚我的代码有什么问题

c++ - 将字符串转换为二进制的最快方法?

c++ - Xalan C++ : returning a node with XPath (reference to local pointer)

c++ - OpenGL 是否仅针对 vSync fps 更新屏幕?

c++ - 如何无限帧率?

c++ - 生成的 TeX 文件中有问题的 '\\+' 序列