假设我们有从抽象类X派生的类A和B.我有一个变量c,如果它是0,则使用A的实例,1使用B的实例。是否可以编写一个函数或if
语句检查c的值并返回相应类型的实例?
答案 0 :(得分:2)
只要将指针强制转换为基类指针,就可以执行此操作。例如,以下工作。
X* create_instance(int type) {
switch (type) {
case 0:
return new A;
case 1:
return new B;
default:
return nullptr; // Or throw for invalid type, or do nothing becaues type is assumed to be valid
}
}
仅用作
int c = ...;
X* p = create_instance(c);
但基本上任何返回指向A
或B
的指针的表达式都会存储在X*
中。这就是为什么DeiDei的评论(c == 0 ? new A : new B;
)能够简明扼要地做同样的事情。
也就是说,拥有原始指针是危险的。在大多数情况下,您应该返回unique_ptr
,除非该对象的生命周期在其他地方进行管理,并且您只需要一个非拥有指针。
答案 1 :(得分:2)
您需要做的是将派生类保存为指向其基类型的指针。通过这种方式,它可以充当它的基类,并且在简单的if else
语句中,您可以在您的问题中实现您想要实现的目标。
这是完整的例子:
#include <iostream>
#include <memory>
class X {
public:
virtual void foo() = 0;
};
class A: public X {
public:
void foo() override { std::cout << "A\n"; }
};
class B: public X {
public:
void foo() override { std::cout << "B\n"; }
};
int main() {
bool what = true;
std::unique_ptr<X> a;
if (what) {
a = std::make_unique<A>();
} else {
a = std::make_unique<B>();
}
a->foo();
return 0;
}
P.S。:如果没有必要,请不要使用new
和原始指针。