C++ 错误代码 C2065:“<class name>”未声明的标识符,即使它应该在另一个 .h 文件中声明

C++ error code C2065: '<class name>' undeclared identifier, even though it should be declared in another .h-file

我有一个多文件程序,我不明白为什么我的程序说 "Customers"(在 registerNewUser() 函数中)是一个未声明的标识符。

proc.h

#ifndef PROC_H
#define PROC_H
#include <iostream>
#include "const.h"
#include "customers.h"
#include <fstream>
using namespace std;

void registerNewUser(Customers cBase); // Add new user.

#endif // !PROC_H

我已经将头文件 (customers.h) 包含在客户 class 中。

customers.h

#ifndef CUSTOMERS_H
#define CUSTOMERS_H
#include <iostream>
#include "const.h"
#include "proc.h"
#include "customer.h"
using namespace std;

class Customers {
    private:
        char* current;
        List* customerList;     // List for customers.
    public:                        
        Customers();            // Constructor.
        ~Customers();           // Destructor.
        void handler();         // Customers handler/menu.
        void addNew(char username[]);
    };

#endif // !CUSTOMERS_H

谁能看出哪里出了问题?

您有一个循环包含。 customers.h 包括 proc.h 所以基本上

void registerNewUser(Customers cBase);

将在编译器看到 Customer 之前添加到 customers.h。看起来你应该能够删除 customers.h 中的 #include "proc.h" 并且它应该编译。

如上面的评论所述,您永远不应在头文件中使用 using namespace std;,因为包含它的任何内容现在都暴露了整个 std 名称空间。您还应该养成只在最狭窄的范围内使用它或完全放弃它的习惯。有关 using namespace std; 用法的进一步阅读,请参阅 Why is “using namespace std” in C++ considered bad practice?

这可能是重复的:你有 proc.h 包括 customers.h 和 customers.h 包括 proc.h 这将导致循环引用,看起来像 proc.h includes in customers 是没有必要的,所以你可以尝试简单地删除这一行:

#include "proc.h"

基本上在 "customers.h" 中包含 "customers.h" 在这里不会有问题,因为你有一个守卫(加分)。不过不是很好看。

正如 NathanOliver 所说,包含的顺序可能有问题,但不一定如此。如果你首先包含 proc.h 一切都很好。如果先包含客户,编译器会在看到客户 class 之前包含 proc.h。 proc 则不会包含 customers.h (因为它的守卫会阻止它)。然后他会发现你的函数不知道 "Customer" 是什么意思。因此,取决于您的头文件的包含顺序,它会或不会起作用。

如果你想要一个提示:我通常首先只包含前向声明所需的文件,然后再进行前向声明。然后我包含定义 class 所需的文件(这些文件已经知道 class 存在)。完整的 class 声明(带有成员函数声明)如下。如果你这样做,你可以避免很多错误。你的情况:

#ifndef CUSTOMERS_H
#define CUSTOMERS_H

class Customers;

#include "proc.h"
#include "ListTool2B.H"
using namespace std;

class Customers 
{
    private:
        char* current;
        List* customerList;     // List for customers.
    public:                        
        Customers();            // Constructor.
        ~Customers();           // Destructor.
        void handler();         // Customers handler/menu.
        void addNew(char username[]);
};

#endif