gpt4 book ai didi

c++ - 类之间的双向引用——如何避免它们相互认识?

转载 作者:行者123 更新时间:2023-11-30 04:22:53 25 4
gpt4 key购买 nike

想象一下,从一个基类派生出多个类。所有类(class)都需要相互了解,这不是一种选择,因为我正在从事的项目更大一些。我将使用虚构的 inventory - item 关系作为示例,因为它很简单。

class Inventory : public Base {
std::vector<Base*> m_items; // These CAN be Items
};

class Item : public Base {
Base* m_parent; // This CAN be Inventory
};

这两个类显然在不同的文件中,它们需要使用彼此的方法,而它们的基类没有。请注意单词 CAN,而不是 MUST,这意味着 m_parent 和 m_items 可以是从 Base 派生的任何类的对象。所以 Item 的父级可以是 InventoryTreasureChest

tl;dr 两个类必须能够相互通信,而无需了解彼此的类型。如何以及什么是实现此类事件的最佳方式?

最佳答案

一种方法是在基类中为通信类型定义一个抽象函数。然后在您的派生类中实现此功能。这使您可以处理所需的每种通信类型。

但是对于两种方式的引用,您在删除此类对象时必须更加小心。这种类型的架构非常容易出错。

对于通信的两种方式引用可能如下所示:基础.h:

class Base {
void doCommunication(Base *caller) = 0;
};

库存.h:

class Inventory;      // forward declaration for Item class
#include "Item.h"

class Inventory : public Base {
void doCommunication(Base *commCaller) {
// check type
Inventory *invCaller = dynamic_class<Inventory*> (commCaller);
if(invCaller != nullptr) {
// called from inventory and you are able to use inventory

return; // you can stop here cause commCaller can only be Base class instead but not Item
}

Item *itemCaller = dynamic_class<Inventory*> (commCaller);
if(invCaller != nullptr) {
// called from item and you are able to use item

return; // you can stop here cause commCaller can only be Base class instead but not inventory
}
}
};

Item.h 看起来与库存类非常相似,必须覆盖 doCommunications 以实现项目特定的功能。

我还不能测试代码,但它应该可以工作。dynamic_cast 的原因是您可以转换为所需的目标对象并调用所需的函数。如果失败,你会得到一个 nullptr。

希望对您有所帮助。

干杯卢卡斯

关于c++ - 类之间的双向引用——如何避免它们相互认识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13574372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com