C++ C++;传递';这';指向基类的指针,然后将其作为子类的另一个基类存储在中
所以我有一个C++ C++;传递';这';指向基类的指针,然后将其作为子类的另一个基类存储在中,c++,inheritance,C++,Inheritance,所以我有一个向量,Base是多个子类的基类,他的一些子类可能是模板类。我想不使用dynamic\u casting从这个基类访问子类,我也不能将基类更改为抽象类。这就是我所做的 struct Ainterface { virtual double GetVal() = 0; }; struct Binterface { virtual bool Getbo() = 0; virtual int Getty() = 0; }; struct Base {
向量
,Base
是多个子类的基类,他的一些子类可能是模板类。我想不使用dynamic\u 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;
}
这样做安全吗?
有没有更好的方法来实现这一点
谢谢当您声明类型为
vector
的变量时,该向量只为classBase
的值分配空间,而不是任何派生类。当你推回一个临时的a
时,它实际上是被切片的,并且变成了一个Base
。GetVal
方法只是在临时驻留的内存尚未回收时意外工作
所以,不,这不是一件安全的事情。这是未定义的行为
如果你想得到一个不同类型的对象向量,你必须使用某种指针。理想情况下,当您声明
vector
类型的变量时,应该使用向量,该向量只为classBase
的值分配空间,而不是任何派生类。当你推回一个临时的a
时,它实际上是被切片的,并且变成了一个Base
。GetVal
方法只是在临时驻留的内存尚未回收时意外工作
所以,不,这不是一件安全的事情。这是未定义的行为
如果你想得到一个不同类型的对象向量,你必须使用某种指针。理想情况下,您可以使用向量
@RSahu,或者复制或分配对象。所以基本上根本不安全,或者复制对象,或者分配对象。所以根本不安全。
5.5