gpt4 book ai didi

c++ - 一个类需要另一个类,另一个类需要第一个类。我怎么做?

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:14 26 4
gpt4 key购买 nike

这里我们有两个类,我们称之为TreeFruitTree 在任何给定时间只能有一个或没有 Fruit。一个 Fruit 只能在一棵 Tree 上。从Tree 对象,您可以通过函数getTreeFruit( ) 获取它的Fruit。从 Fruit 对象,您可以通过返回 Tree 对象的函数 getFruitOwner( ) 获取它的“所有者”。

现在在 Tree header 中,我们有这个:

#include "Fruit.h"
class Tree {
private:
Fruit m_Fruit; // The fruit in the tree.

public:
Tree ( Fruit tree_fruit );
Fruit getTreeFruit( ); // Returns m_Fruit.
}

Fruit header 上:

#include "Tree.h"
class Fruit {
private:
Tree m_Owner; // The Tree object that "owns" the fruit.

public:
Fruit ( Tree fruit_owner );
Tree getFruitOwner( ); // Returns m_Owner.
}

我意识到 TreeFruit 包含彼此的头文件,这会导致错误。我该如何修复错误?

非常感谢。 :)

最佳答案

您应该在 Fruit 对象中存储对树的引用,而不是树本身。

在这里引用比指针更好,因为它们表达了水果不能神奇地从一棵树跳到另一棵树的条件。引用只能在构造对象时设置,因此您必须在构造函数中使用初始化列表。

然后,您可以使用 Tree 的前向声明。

  class Tree;

class Fruit {
private:
Tree &owner; // The Tree object that "owns" the fruit.

public:
Fruit (Tree &fruit_owner ) : owner(fruit_owner)
{ ... };

Tree &getFruitOwner( ); // Returns owner.

关于c++ - 一个类需要另一个类,另一个类需要第一个类。我怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11793242/

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