假设我要这样做:
type variable;
if(condition1){
variable= something of class A
}
else if(condition2){
variable = something of class B
}
do more with / variable
我该如何实现?
最佳答案
只要您的A
和B
类具有相同的基础,就可以使用指针进行类似的操作。像这样:
class Base {
//...
public:
virtual ~Base() {} // MUST have VIRTUAL member for dynamic_cast
};
class A : public Base {
//...
public:
virtual ~A() {}
};
class B : public Base {
//...
public:
virtual ~B() {}
};
// ...
bool condition = true;
Base* variable;
if (condition)
variable = new A;
else
variable = new B;
//...
一旦创建了类对象(并提供了至少一个虚函数),您就可以在后面的代码中使用
dynamic_cast
运算符“询问”它实际上是哪种类型的对象: // ... continuing in the same scope as the previous code...
if (dynamic_cast<A*>(variable) != nullptr) { // Points to an A object:
// Do something specific to A
// A* ptrA = dynamic_cast<A*>(variable);
// ptrA->member = value;
}
else if (dynamic_cast<B*>(variable) != nullptr) { // Points to a B object:
// Do something specific to B
}
else { // Not an A or a B...
// (error handling?)
}
//...
// And, of course, don't forget to free the object when finished:
delete variable;
关于c++ - 取决于var类型的if循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61211394/