繁体   English   中英

错误:类名未命名 C++ 中的类型

[英]Error: class name does not name a type in C++

我知道这个问题已经被问过很多次了,但我已经尝试了一些建议,比如检查我的拼写,确保我包含了头文件,大小写等,但我仍然遇到同样的错误并且无法弄清楚找出触发它的原因。

当我尝试使用 g++ -c Customer.h 编译 Student.h 时,出现错误“Student”没有在“Student student;”行上命名类型对于 Login.h,我不知道为什么。 任何人都可以尝试查明是什么原因造成的吗? 这个变量应该代表这个登录 ID/帐户的学生,它应该是一个指向 Student 对象的指针。

同样,当我尝试编译 Login.h 时,我收到错误 'Login' has not been denied in Customer.h for bool addAcct(Login*) 以及错误 'Login' does not have a type for Login* logins [MAX_LOGINS]。

任何帮助,将不胜感激!

学生.h:

#ifndef STUDENT_H
#define STUDENT_H
#define MAX_LOGINS 4
#include <string>
#include "Login.h" 
using namespace std;

class Student{
    public:
        Student(int = 0, string = ""); 
        int getId();
        bool addAcct(Login*);
        void print();
    private:
        int id;
        string name;
        Login* logins[MAX_LOGINS];
        int numberOfLogins;
};
#endif

登录.h

#ifndef LOGIN_H
#define LOGIN_H
#include <string>
#include "Student.h"
using namespace std;

class Login{
    public:
        Login(int = 0, float = 0); 
        int getNumber();
        void setStudent();
        void print();
    private:
        int number;
        Student student;
};
#endif

这里的问题是循环依赖(如评论中所指出的),问题在于处理器本质上将#include语句作为顺序文本插入处理。

例如,当预处理器遇到#include "student.h" ,它会一步一步地像这样:

#ifndef STUDENT_H  // <--- header guard not defined at this point, ok to proceed
#define STUDENT_H  // <--- define header guard first thing in order to prevent recursive includes
#define MAX_LOGINS 4
#include <string>
#include "Login.h"  --->  #ifndef LOGIN_H
                          #define LOGIN_H
                          #include <string>
                          #include "Student.h"  --->  #ifndef STUDENT_H
                                                      // entire body of student.h is skipped over
                                                      // because STUDENT_H header guard is defined
                          using namespace std;  <---  // so processing continues here

                          class Login{
                          // ...
                          Student student;   // <--- error because class Student is not defined
                          };

解决方案是转发不需要完整定义的声明类型,而不是#include 'ing 相应的标头。

在这种情况下, class Login有一个成员Student student; 这需要完全定义class Student ,因此login.h实际上必须#include "student.h"

然而, class Student只携带Login* logins[MAX_LOGINS]; 指向Login的指针数组,指针不需要类的完整定义,而只需要类型的前向声明。 因此, Student.h可以修改为转发声明class Login ,从而消除循环头依赖并允许代码编译。

// #include "Login.h"  // <--- full header not required

class Login;           // <--- forward declaration is sufficient

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM