【问题标题】:Global structs not being seen未看到全局结构
【发布时间】:2009-08-15 16:06:37
【问题描述】:

定义为:Class.h

#ifndef CLASS_H_
#define CLASS_H_

#include "Class2.h"    
#include <iostream>

struct Struct1{
};

struct Struct2{
};

class Class1 {
};

#endif 

然后是我使用的另一个头文件:

#ifndef CLASS2_H_
#define CLASS2_H_

#include "Class.h"

class Class2 {
    public:
        Class2( Struct1* theStruct, Struct2* theStruct2); //Can't find struct definitions
    private:
};

#endif 

它们在同一个目录中。它没有看到那些结构定义!对我来说,它们似乎在全球范围内。有人可以向我解释为什么 Class2 看不到它们吗?编译器并没有抱怨找不到 Class 的头文件,所以不可能是这样。

【问题讨论】:

  • 这似乎不是全部代码。你试过那个确切的代码吗? &lt;iostream&gt; 在哪里使用?

标签: c++ mingw


【解决方案1】:

接下来是对您的完整代码的猜测。请张贴,然后我们可以更好地帮助你。


如果您的完整代码如下所示,那么您应该更改它

#ifndef CLASS_H_
#define CLASS_H_

#include <iostream>
#include "Class2.h"

struct Struct1{
};

struct Struct2{
};

class Class1 {
};

#endif

因为已经定义了CLASS_H_ 宏,所以在Class2.h 中将不会再包含另一个标头,然后在那时Struct1Struct2 将是未知的。尽可能使用前向声明来修复它。比如Class2.h:

#ifndef CLASS2_H_
#define CLASS2_H_

// no need for that file
// #include "Class.h"

// forward-declarations suffice    
struct Struct1;
struct Struct2;

class Class2 {
    public:
        Class2( Struct1 theStruct, Struct2 theStruct2);
    private:
};

#endif

如果另一个头文件也不需要Class2 的定义,那么也可以使用前向声明。不需要定义(即声明就足够了)

  • 引用和指针
  • 函数声明中的函数参数不是定义

如果您想要访问成员、想要获取sizeof 或想要定义具有Class2Struct1 等参数类型的函数,则需要它。

【讨论】:

  • 你先生,是通灵者。那么问题来了,如果我想在Class中存储一个Class2,我该如何在头文件中引用呢?
  • 你将需要包含标题然后:) 但是,你将不得不设法不需要来自另一个标题的标题然后打破圆圈:) 如果它不能打破,你将不得不使用指针并使用new 在.cpp 文件中分配对象。试试shared_ptr :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2015-07-16
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多