c++ - 如何设计我的类(class)?

标签 c++ c++11

我有两个继承相同抽象基类的类:

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?

我希望使用该类(class)的人有可能这样做:

a a_obj;
b b_obj;

b_obj.obj_ptrs.push_back(a);
b_obj.obj_ptrs.push_back(b);

我应该如何设计我的类来完成这项工作?

最佳答案

I could use a list of raw/smart pointers (list<base*> obj_ptrs), but how to use this list?

您可以通过调用虚函数或在特殊情况下使用 dynamic_cast 与它们进行多态交互将指针类型转换为 a*b* .

Who have to delete this pointer?

您必须决定所有权方案。一种方法是在列表中存储智能指针(通常是 unique_ptr ,或者在特殊情况下可能是 shared_ptr ),然后它们会在从列表中删除时自动删除。另一种方法是将对象与列表分开管理,只将原始指针放在列表中。

// The following is valid for c++11
auto p = b_obj.obj_ptrs.back();
// But if i'm using c++03?

这相当于 base * p = b_obj.obj_ptrs.back(); . auto不会神奇地给出动态指针类型,它只是静态指针类型的快捷方式。

How have I to design my classes to do this work? (storing objects of different types)

可以使用区分 union 来存储不同类型的对象 - 基本上, union 具有一些额外的元数据以跟踪哪个 union 成员处于事件状态。这些在 C++ 中实现起来非常棘手,但您可以使用 Boost.VariantBoost.Any .这样做的好处是您不需要公共(public)基类,也不需要存储类型的任何其他支持;可以使用任何一组(非抽象)类型。

关于c++ - 如何设计我的类(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344530/

相关文章:

c++ - 如何将字符串与回车符 0x0D 进行比较?

c++ - 使用 __declspec 的内存填充问题

c++ - constexpr std::array with static_assert

c++ - 预期 { 在析构函数之前

c++ - 使用 const 成员函数 boost type_erasure any

c++ - 是否有任何用于 C++ 的跨平台 GUI 库(具有平台相关的 UI 和基于脚本的布局)?

c++ - 友元函数中的 STL 问题

c++ - C++0x 的库计划?

c++ - 相同类型重新定义的 Clang typedef(和别名)导致意外错误

python - 带有智能指针的 Swig 类型图