类名未在C ++中命名类型 [英] Class name does not name a type in C++
问题描述
我刚刚开始用C ++编程,我试图创建2个类,其中一个包含另一个类。
I just started programming in C++, and I've tried to create 2 classes where one will contain the other.
文件 Ah
:
#ifndef _A_h
#define _A_h
class A{
public:
A(int id);
private:
int _id;
B _b; // HERE I GET A COMPILATION ERROR: B does not name a type
};
#endif
文件 A.cpp
:
#include "A.h"
#include "B.h"
#include <cstdio>
A::A(int id): _id(id), _b(){
printf("hello\n the id is: %d\n", _id);
}
文件 Bh
:
#ifndef _B_h
#define _B_h
class B{
public:
B();
};
#endif
文件 B.cpp
:
#include "B.h"
#include <cstdio>
B::B(){
printf("this is hello from B\n");
}
我先编译B类,然后编译A类,但随后得到错误消息:
I first compile the B class and then the A class, but then I get the error message:
Ah:9:错误: B未命名类型
A.h:9: error: ‘B’ does not name a type
如何解决此问题?
推荐答案
预处理器插入内容 Ah
和 Bh
文件中的 include
语句的确切位置发生(这实际上只是复制/粘贴)。当编译器然后解析 A.cpp
时,它会在知道类<$ c之前找到类 A
的声明。 $ c> B 。这会导致您看到错误。有两种解决方法:
The preprocessor inserts the contents of the files A.h
and B.h
exactly where the include
statement occurs (this is really just copy/paste). When the compiler then parses A.cpp
, it finds the declaration of class A
before it knows about class B
. This causes the error you see. There are two ways to solve this:
- 在<$ c $中包含
Bh
c> Ah 。通常,将头文件包含在需要它们的文件中是一个好主意。如果您依赖于通过另一个标头间接包含或在编译单元(cpp文件)中包含特殊顺序,则只会在项目变大时使您和其他人感到困惑。 -
如果在类
A
中使用类型为B
的成员变量,则编译器需要知道确切且完整的信息声明B
,因为它需要为A
创建内存布局。另一方面,如果您使用的是指向B
的指针或引用,则前向声明就足够了,因为编译器需要为指针或引用保留内存与类定义无关。看起来像这样:
- Include
B.h
inA.h
. It is generally a good idea to include header files in the files where they are needed. If you rely on indirect inclusion though another header, or a special order of includes in the compilation unit (cpp-file), this will only confuse you and others as the project gets bigger. If you use member variable of type
B
in classA
, the compiler needs to know the exact and complete declaration ofB
, because it needs to create the memory-layout forA
. If, on the other hand, you were using a pointer or reference toB
, then a forward declaration would suffice, because the memory the compiler needs to reserve for a pointer or reference is independent of the class definition. This would look like this:
class B; // forward declaration
class A {
public:
A(int id);
private:
int _id;
B & _b;
};
这对于避免标题之间的循环依赖非常有用。
This is very useful to avoid circular dependencies among headers.
我希望这会有所帮助。
这篇关于类名未在C ++中命名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!