【问题标题】:Class Name does not declare type C++类名未声明类型 C++
【发布时间】:2014-03-25 07:11:06
【问题描述】:

我正在尝试编译我的代码,但遇到类错误。其中一个类编译得很好(Example.h),但另一个(Name.h)一直给我这个类没有命名类型错误。我认为这与循环依赖有关,但是如果没有向前减速,我该如何解决呢?

名称.h

#ifndef _NAME
#define _NAME
#include <iostream>
#include <string>
using namespace std;
#include "Example.h"
class Name{
};
#endif

Example.h

#ifndef _EXAMPLE
#define _EXAMPLE
#include <iostream>
#include <string>
using namespace std;
#include "Name.h"
class Example{

};
#endif

我看到了一篇关于使用正向减速的帖子,但是我需要从 Example 类中访问成员..

【问题讨论】:

  • 您不能在B.h 中包含A.h,在A.h 中包含B.h。确实是循环依赖。您可以尝试前向声明类。
  • 但是前向声明会让我访问其他类的成员函数吗?
  • 与这个问题无关,但由于您(大概)使用现代 C++ 编译器,您可以取消过时的 #ifndef _EXAMPLE #define _EXAMPLE #endif 事情。只需使用#pragma once。 (en.wikipedia.org/wiki/Pragma_once)
  • @user2351234 不,类A 的前向声明仅允许您在B.h 文件中声明指向A 的指针。但是您可以在B.cpp 中包含来自A.hA 的整个声明。
  • @cmbasnett: #pragma once 是非标准的,并非所有现代编译器都支持,因此使用可移植的#ifndef / #define 包含警卫是完全合理和正确的,前提是只允许选择的名称由用户程序。

标签: c++ class compiler-errors


【解决方案1】:

你有一个循环依赖,每个标题都试图包含另一个,这是不可能的。结果是一个定义在另一个之前结束,第二个的名称在第一个中不可用。

在可能的情况下,声明每个类而不是包括整个标题:

class Example; // not #include "Example.h"

如果一个类实际上包含(或继承自)另一个类,您将无法做到这一点;但这将允许在许多声明中使用该名称。由于两个类不可能包含另一个类,因此您至少可以对其中一个类执行此操作(或者可能只是完全删除 #include),这应该会打破循环依赖并解决问题。

另外,不要将reserved names_NAME 一样使用,也不要将pollute the global namespaceusing namespace std; 一起使用

【讨论】:

    【解决方案2】:

    看,这里您将#include "Example.h" 包括在Name.h#include "Name.h"Example.h 中。假设编译器首先编译Name.h 文件,所以现在定义了_NAME,然后它尝试编译Example.h,这里编译器想要包含Name.h,但Name.h 的内容不会包含在Example.h 中,因为@987654331 @ 已定义,因此 class Name 未在 Example.h 中定义。

    您可以在Example.h 内显式地进行class Name; 的前向声明

    【讨论】:

      【解决方案3】:

      试试这个:

      名称.h

      #ifndef NAMEH
      #define NAMEH
      #include <iostream>
      #include <string>
      using namespace std;
      
      //#include "Example.h"
      class Example;
      
      class Name{
      };
      #endif
      

      名称.cpp

      #include "Name.h"
      #include "Example.h"
      ...
      

      Example.h

      #ifndef EXAMPLEH
      #define EXAMPLEH
      #include <iostream>
      #include <string>
      using namespace std;
      
      //#include "Name.h"
      class Name;
      
      class Example{
      
      };
      #endif
      

      Example.cpp

      #include "Example.h"
      #include "Name.h"
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        相关资源
        最近更新 更多