如何使用在包含使用该符号的文件的文件中声明的符号(函数、字段、类 等)。 C++

How to use symbols(functions, fields, classes & etc.) declared in a file that includes file where the symbol is used. C++

我有一个函数、字段等(我们称它为符号a)在文件中声明A.h,这个a在文件B.h中使用,所以B.h包含A.h。但是 A.h 使用另一个 函数、字段等 (我们称它为 符号 b)来自 B.h,因此 A.h 包括 B.h。理论上它是允许工作的,因为这些符号可能不是相互存储的变量或相互调用使无穷大的函数"recursion"。但是没用。

我想说的是一个真实的例子。我没有在其中包含所有不相关的细节以及两个文件中声明和实现的分离。

文件Application.h:

#ifndef APP_H
#define APP_H

#include "Log.h"

class Application
{
public:
    static void exception(std::string description)
    {
        Log::print("Program throwed: " + description);
        throw description;
    }
};

#endif // APP_H

文件Log.h:

#ifndef  LOGG_H
#define LOGG_H

#include "Application.h"
#include <string>
#include <iostream>

class Log
{
public:
    static void print(std::string message)
    {
        if (message.size() > 200)
        {
            Application::exception("Message is too long");
        } else
        {
            std::cout << __TIME__ << " >> \t " << message << std::endl;
        }
    }
};

#endif // LOGG_H

文件Main.h:

#include "Application.h"
#include "Log.h"

int main()
{   
 Log::print("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
    // There are over 200 charcaters. Then it will call method Application::exception from Log::print

    return 1;
}

结果:

文件 Log.h:

中第 17 行 (Application::exception("Message is too long");) 的 C2653

应用程序:不是 class 或命名空间名称

文件 Log.h:

中第 17 行 (Application::exception("Message is too long");) 的 C3861

异常:未找到标识符

您需要打破包含循环。

将代码从 header 之一移动到匹配的 .cop 文件中。从 header 中删除 #include。将其移至 .cpp 文件。

Forward-declare 根据需要。