所以我有一个vector<Base>
而Base
是多个孩子的基类,他的一些孩子可能是模板类。我想从这个基类访问子类而不使用dynamic_casting
我也不能将基类更改为抽象类。这就是我做的事情
struct Ainterface {
virtual double GetVal() = 0;
};
struct Binterface {
virtual bool Getbo() = 0;
virtual int Getty() = 0;
};
struct Base {
Base(int id, Ainterface* inter):
id_(id),
a_interface_(inter){}
Base(int id, Binterface* inter):
id_(id),
b_interface_(inter){}
int id_;
Ainterface* a_interface_;
Binterface* b_interface_;
};
struct A : Base, Ainterface {
A():
Base(1, this),
val(5.5){}
double val;
double GetVal(){return val;}
};
template<typename T>
struct B : Base, Binterface {
B():
Base(2, this),
ty(5){}
int ty;
bool Getbo(){ return t_class.get();}
int Getty(){ return ty;}
T t_class;
};
...
...
int main(){
std::vector<Base> base;
base.push_back(A());
auto some = base.back();
switch (some.id_) {
case 1:
std::cout << some.a_interface_->GetVal() << std::endl;
break;
case 2:
std::cout << some.b_interface_->Getbo() << some.b_interface_->Getty() << std::endl;
default:
break;
}
return 0;
}
输出
5.5
这是安全的吗? 有没有更好的方法来实现这一目标?
由于
答案 0 :(得分:4)
当声明类型为vector<Base>
的变量时,向量仅为类Base
的值分配空间,而不是任何派生类。当您推回临时A
时,它实际上已被切片并变为Base
。 GetVal
方法只能作为临时驻留的内存尚未被回收的事件。
所以,不,这不是一件安全的事情。它是未定义的行为。
如果您想要一个可以在类型上变化的对象矢量,则必须使用某种指针。理想情况下,您可以使用vector<shared_ptr<Base>>
。