我一直收到一个错误,说我的班级没有命名类型

时间:2011-02-03 20:54:29

标签: c++ class

我有一个名为A的类,它有自己的头文件。然后我有另一个名为B的类,它也有自己的头文件。它们每个都有自己的.cpp文件,我实现了它们的所有功能。

我试图让B类有一个类型A的变量作为私有变量,但我不断收到错误'A'没有命名类型

我的代码如下所示:

main.h:

#ifndef MAIN_H
#define MAIN_H

#include "A.h"
#include "B.h"

#endif

main.cpp中:

#include "main.h"

int main( int argc, char* args[]) {
  B test;
}

A.H:

#ifndef A_H
#define A_H

#include "main.h"

class A {
  public:
    //public functions
  private:
    //private variables
};
#endif

B.h:

#ifndef B_H
#define B_H

#include "main.h"

class B {
  public:
    //public functions...
  private:
    A temp;
}
#endif

所以我的所有包含都在main.h中,其中包括A之前的B.B有一个A类型的变量,但它包含在main.h中,而B.h包含main.h.但是,我一直收到错误说:

error: 'A' does not name a type.

我做了一些谷歌搜索,似乎这意味着当你使用它时没有定义A,但它应该在那里定义,因为它被包含在main.h中,对吗?

3 个答案:

答案 0 :(得分:8)

问题在于A.h包含main.h,其中包含B.h,其中包含A

组织文件的好方法是:

main.h:

// not needed

main.cpp中:

#include "B.h" // for using class B

int main( int argc, char* args[]) {
  B test;
}

A.H:

#ifndef A_H
#define A_H

// no includes needed ATM

class A {
  //...
};
#endif

B.h:

#ifndef B_H
#define B_H

#include "A.h" // for using class A

class B {
  //public functions...
}
#endif

这样,B.h 自包含 ,无需在其中包含任何其他内容即可使用。一旦你的项目超过目前的玩具水平,这一点非常重要。为什么有人试图使用标题x.h提供的需要知道还包括f.hm.hu.h

答案 1 :(得分:2)

如果你添加一个,你提供的代码会正确编译;在B.h结束时

更好的方法是在“B.h”中添加#include“A.h”,而不是#include“main.h”

但这可能与你的问题无关。

如果您使用模板并忘记“typename”,那种错误也可能会造成混淆。

答案 2 :(得分:0)

A.h包括Main.h。

Main.h跳过A.h,因为A_H已经定义,然后包括B.h。

B.h尝试使用A,但A.h尚未完成编译,因此未定义类型。