【发布时间】:2014-03-25 07:11:06
【问题描述】:
我正在尝试编译我的代码,但遇到类错误。其中一个类编译得很好(Example.h),但另一个(Name.h)一直给我这个类没有命名类型错误。我认为这与循环依赖有关,但是如果没有向前减速,我该如何解决呢?
名称.h
#ifndef _NAME
#define _NAME
#include <iostream>
#include <string>
using namespace std;
#include "Example.h"
class Name{
};
#endif
Example.h
#ifndef _EXAMPLE
#define _EXAMPLE
#include <iostream>
#include <string>
using namespace std;
#include "Name.h"
class Example{
};
#endif
我看到了一篇关于使用正向减速的帖子,但是我需要从 Example 类中访问成员..
【问题讨论】:
-
您不能在
B.h中包含A.h,在A.h中包含B.h。确实是循环依赖。您可以尝试前向声明类。 -
但是前向声明会让我访问其他类的成员函数吗?
-
与这个问题无关,但由于您(大概)使用现代 C++ 编译器,您可以取消过时的
#ifndef _EXAMPLE #define _EXAMPLE #endif事情。只需使用#pragma once。 (en.wikipedia.org/wiki/Pragma_once) -
@user2351234 不,类
A的前向声明仅允许您在B.h文件中声明指向A的指针。但是您可以在B.cpp中包含来自A.h的A的整个声明。 -
@cmbasnett:
#pragma once是非标准的,并非所有现代编译器都支持,因此使用可移植的#ifndef / #define包含警卫是完全合理和正确的,前提是只允许选择的名称由用户程序。
标签: c++ class compiler-errors