【发布时间】: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 文件中通常很好,但基本上从不在头文件中使用它,因为它会污染任何想要使用您的类的人的名称空间(在某些时候可能包括您) .