C++:两个相互引用的类

Posted

技术标签:

【中文标题】C++:两个相互引用的类【英文标题】:C++: Two classes referencing each other 【发布时间】:2013-12-06 07:48:58 【问题描述】:

所以为了玩弄朋友功能,我决定创建一个Child 类和一个Mother 类。 Mother 类有一个 Child 数据成员。 Child 类创建了 Mother 类友元函数的两个方法。

但是,当我编译时,似乎无论我如何处理包含,我最终都会出错。如果 Child 是第一个被定义的,我得到 "Mother is not a class or namespace name" 用于 Child.h 中的 friend void Mother::setChildName(string name); 行。如果 Mother 是第一个被定义的,我会在 Mother.h 中得到 Child c; 行的“Missing type specifier”。

有没有办法解决这个问题?我尝试将 class Mother; 放在 Child.h 的顶部,将 class Child; 放在 Mother.h 的顶部,但这似乎没有帮助。

或者这种循环引用总是会失败?

在 Mother.h 中:

#ifndef MOTHER_H_
#define MOTHER_H_

#include <string>
#include "Child.h"

using namespace std;

class Mother 
public:
    Mother();

    void setChildName(string name);

    string getChildName();

private:
    Child c;
;

#endif

在 Mother.cpp 中:

#include <string>
#include "Mother.h"

using namespace std;

void Mother::setChildName(string name) 
    c.name = name;


string Mother::getChildName() 
    return c.name;

在 Child.h 中:

#ifndef CHILD_H_
#define CHILD_H_

#include <string>
#include "Mother.h"

using namespace std;

class Child 
public:

private:
    string name;

    friend void Mother::setChildName(string name);
    friend string Mother::getChildName();
;

#endif

【问题讨论】:

请避免使用命名空间标准;在全球范围内 using namespace std; 在 .cpp 文件中通常很好,但基本上从不在头文件中使用它,因为它会污染任何想要使用您的类的人的名称空间(在某些时候可能包括您) . 【参考方案1】:

如果不重新设计,这个特殊问题就无法解决。 Mother 需要在 Child 之前定义,Child 需要在 Mother 之前定义。简单的方法是让整个 Mother 班级成为 Child 的朋友。这样就可以先定义 Child。

我认为让单个方法成为另一个类的朋友并没有什么实际好处。这意味着你的班级太大了,它的职责可以分成更小的班级。

【讨论】:

我不确定将 friend class Mother; 的两个友元函数语句切换为重新设计是否完全公平。课程基本相同,他的目标也很接近。【参考方案2】:

如果母亲将持有指向孩子的指针,您将不必包含 child.h。向前减速就足够了。

【讨论】:

以上是关于C++:两个相互引用的类的主要内容,如果未能解决你的问题,请参考以下文章

C++中两个类相互包含引用问题

C++的=重载问题,怎样为两个有相同成员的类赋值

两个类(C++)中的类到类转换 - 前向声明?

如何声明相互引用的类?

使用哈希模板特化相互引用的两个类

相互引用的两个类