小编Dav*_*ass的帖子

从派生类c ++获取变量

我希望只有在类是特定的派生类时才能做某事.那就是我:

class X{
    int id;
}

class A: public X{
    void run();
}

class B: public X{
    int lala;
}
Run Code Online (Sandbox Code Playgroud)

我想做一些事情:

main(){
    vector<X *> types;
    types.push_back(new A);
    types.push_back(new B);
    int var = 0;
    for(int i = 0; i<types.size(); i++){
        if(types[i].isType(A)) {types[i].run();} 
    }
    for(int i = 0; i<types.size(); i++){
        if(types[i].isType(B)) {var = lala;} 
    }
}
Run Code Online (Sandbox Code Playgroud)

我不希望B类有任何等同于run()的东西,也不希望A类具有等同于lala的东西.

我知道fortran有一个解决方法

select type ( x => var )
class is ( A )
    x.run()
end select
Run Code Online (Sandbox Code Playgroud)

但我不确定我在C++中的选择是什么.

谢谢

c++ oop class derived

2
推荐指数
1
解决办法
94
查看次数

标签 统计

c++ ×1

class ×1

derived ×1

oop ×1