簡體   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