【问题标题】:C++ base class pointers, collection classesC++基类指针、集合类
【发布时间】:2023-03-20 13:52:01
【问题描述】:

我有一个 Animal 的基类和 Dog、Cat 的派生类。

我还有一个 DogCollection、CatCollection 类来管理操作,例如添加一只新猫等、读取一只猫、从数据库中删除一只猫、使用指向 Dog 和 Cat 类的指针搜索特定的猫。

有人要求我使用基类指针来管理单个容器中的类。为此,在 Dog 和 Cat 类中执行读写操作而不是在单独的 DogCollection 和 CatCollection 类中执行读取和写入操作是否更好?

【问题讨论】:

  • 请显示一些代码。你的最后一段让我有点困惑。我明白这是家庭作业。听起来您被要求使用 AnimalCollection 而不是 DogCollectionCatCollection,但我无法理解您的最后一个问题。
  • 我的理解是,您被要求拥有一个指向 Animal 的指针容器,您可以在其中存储指向 Dogs 和 Cats 的指针。所以,我想,你说的是虚拟调度。
  • 相信你要找的是Dog wMyDog;Animal * wAnimal = wMyDog;

标签: c++ inheritance polymorphism


【解决方案1】:

在常见的 c++ 中,您通常会使用模板化容器来保存对象,如下所示:

#include <vector>

class Cat;
class Dog;
class Animal;

typedef std::vector<Cat*> CatCollection;
typedef std::vector<Dog*> DogCollection;
typedef std::vector<Animal*> AnimalCollection;

我使用std::vector 作为容器,但还有其他可用的。

然后您将容器作为容器进行操作并对项目本身执行操作,例如:

AnimalCollection coll;

//add elements
Cat *cat = ...;
Dog *dog = ...;

coll.push_back(cat);
coll.push_back(dog);

//do something with the first item of the collection
coll[0] -> doStuff();

//do something on all items
for (Animal *c: coll) {
    c -> doStuff();
}

//Don't forget to delete allocated objects one way or the other
//std::vector<std::unique_ptr<Animal>> can for example take ownership of pointers and delete them when the collection is destroyed

在特殊情况下可以为特定类型创建特定集合类,但并不常见。

Live Demo

【讨论】:

  • 这取决于您可能需要对实例执行特定操作或您希望封装在不同类中的某些数组操作。
  • @coyotte508 doStuff() 属于哪个类?
  • 如果它是virtual 并且在子类CatDog 中被覆盖,则将调用CatDog 的那个。我很快就会用一个实时示例进行编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
相关资源
最近更新 更多