我有兩個類,繼承相同的抽象基類:如何設計我的課程?
class base
{ virtual void something() = 0; };
class a : public base
{
void something();
};
class b : public base
{
void something();
// This is what I want: a list where I can store values of type a
// and of type b
// std::list<a & b> objs;
};
我可以使用原始/智能指針(list<base*> obj_ptrs
)的名單,但如何使用這個名單?
b b_obj;
b_obj.obj_ptrs.push_back(new a());
// Who have to delete this pointer? Who use the class or who design
// the class in the object destructor?
// The following is valid for c++11
auto p = b_obj.obj_ptrs.back();
// But if i'm using c++03?
我想是誰使用的類必須這樣做的可能性:
a a_obj;
b b_obj;
b_obj.obj_ptrs.push_back(a);
b_obj.obj_ptrs.push_back(b);
如何有我設計我的類來完成這項工作?
當我想要回最後一個對象時,我怎麼知道我是否必須編寫'a * aPtr = dynamic_cast(b_obj.obj_ptrs.back());'或'b * bPtr = dynamic_cast (b_obj.obj_ptrs.back ());',即我怎麼知道我的對象在列表中的類型是什麼? – Nick 2012-07-05 20:36:32
@Nick:你不知道類型,這就是爲什麼通常使用虛函數來完成多態的原因。你必須嘗試每種類型:'if(a * p = dynamic_cast (b_obj.obj_ptrs.back()){/ *它是一個「a」* /}'。正如我在答案中所說的那樣,情況,當你不能讓虛擬功能爲你工作。 – 2012-07-05 22:54:55