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

kre*_*rej 0 c++ class

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

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

我的代码看起来像这样:

main.h:

#ifndef MAIN_H
#define MAIN_H

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

#endif
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include "main.h"

int main( int argc, char* args[]) {
  B test;
}
Run Code Online (Sandbox Code Playgroud)

啊:

#ifndef A_H
#define A_H

#include "main.h"

class A {
  public:
    //public functions
  private:
    //private variables
};
#endif
Run Code Online (Sandbox Code Playgroud)

BH:

#ifndef B_H
#define B_H

#include "main.h"

class B {
  public:
    //public functions...
  private:
    A temp;
}
#endif
Run Code Online (Sandbox Code Playgroud)

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

error: 'A' does not name a type.
Run Code Online (Sandbox Code Playgroud)

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

sbi*_*sbi 8

问题是A.h包括main.h,包括B.h,试图使用A.

组织文件的好方法是:

main.h:

// not needed
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

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

int main( int argc, char* args[]) {
  B test;
}
Run Code Online (Sandbox Code Playgroud)

啊:

#ifndef A_H
#define A_H

// no includes needed ATM

class A {
  //...
};
#endif
Run Code Online (Sandbox Code Playgroud)

BH:

#ifndef B_H
#define B_H

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

class B {
  //public functions...
}
#endif
Run Code Online (Sandbox Code Playgroud)

这样,它B.h独立的,可以在不必在其之前包含任何其他内容的情况下使用.一旦你的项目超过目前的玩具水平,这一点非常重要.为什么会有人试图用什么标题x.h提供需要知道的还包括f.h,m.hu.h