[英]How to identify elements in array or matrix and work with them correctly? c++
首先,我有抽象父类:
class Abstract_class {
virtual void Method1() {
std::cout<<"Method1 of abstract class!\n";
}
};
我也有儿童班
class Child1: public Abstract_class {
void Method1() override {
std::cout<<"Method1 of child1 class!\n";
}
};
class Child2: public Abstract_class {
void Method1() override {
std::cout<<"Method1 of child2 class!\n";
}
};
我的主要功能
int main(){
Abstract_class ** arr = new Abstract_class * [10];
for(int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
Abstract_class * obj;
// pseudo random rules for fill array
if (i%2 == 0) {
arr[i] = new Child1();
}
else {
arr[i] = new Child2();
}
}
}
}
现在,假设我对这个数组执行一些操作,引用元素,我需要知道哪个,对象所在的位置,这样就不存在我期望 Method1 像在 child1 中那样执行的情况,但是我获得完全不同的 child2 方法实现。 当然,你总是可以在类中添加字段来标识一个对象,但是我想要一些符合 OOP 规则的优雅的东西
您可以为此使用动态演员表:
Abstract_class *someObj = ...;
if(Child1 *c1 = dynamic_cast<Child1>(someObj)) {
c1->specificChild1Func();
}
但是,您不应该需要这样的东西。 多态性的要点是您可以不知道底层类型是什么,但仍然可以使用它们。 您正在寻找这一事实可能表明您需要进行设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.