通过头文件C ++使用多个结构

时间:2015-03-22 19:25:21

标签: c++ vector struct

如果您之前已经看过这个问题但是还没有得到解答,请道歉。基本上在我的代码中我有两个结构,在单独的标题中定义并在整个项目中全局使用。我只是希望在其他cpp文件中使用两个结构(在两个单独的头文件中定义),而不仅仅是头文件所属的结构。 以下是我测试的一些示例代码:

class1.h

    #include "class2.h"
    #include <vector>
    #include <string>

    struct trans1{
        string name;
    };
    class class1 {

    private:
        vector <trans2> t2;

    public:
        class1();
    };

class2.h

    #include "class1.h"
    #include <vector>
    #include <string>        

    struct trans2{
        string type;
    };

    class class2{

    private:
        vector <trans1> t1;

    public:
        class2();
    };

错误日志:

    In file included from class1.h:3:0,
                     from class1.cpp:1:
    class2.h:21:13: error: 'trans1' was not declared in this scope
         vector <trans1> t1;
                 ^
    class2.h:21:19: error: template argument 1 is invalid
         vector <trans1> t1;
                       ^
    class2.h:21:19: error: template argument 2 is invalid

我知道这在现实世界的应用程序中是荒谬的代码,但这是我演示的最简单的方法。

值得注意的是,如果我只是简单地在“私人”下注释出向量t1或t2的声明:&#39;代码编译必定。这只是我使用第二个结构的事实。

有人帮忙吗?感谢。

4 个答案:

答案 0 :(得分:1)

简单地向前声明将要使用的类。将所有实现代码放入cpp文件中,而不是标题中的内联。

将矢量设为私有。这样,包含标头的文件就不会强制代码生成不完整的类。

答案 1 :(得分:0)

你可以尝试在class2.h中转发声明trans1,在class1.h中转发trans2,如下所示:

class2.h:

// includes
struct trans1;
// rest of your code
在class1.h

中同样的事情(但使用trans2)

不要忘记在代码中添加Include警卫!

  • 编辑:是的,您需要更改向量以存储指针,否则无法链接

答案 2 :(得分:0)

如果您要在单个.cpp文件中执行此操作,解决方案将是微不足道的:

   struct trans1 { ... };
   struct trans2 { ... };
   class class1 { ... };
   class class2 { .... };

现在您只需重新排列代码即可在每个翻译单元中获得此结果。 (文件中类/结构的顺序很重要)

答案 3 :(得分:0)

你需要把&#34; trans&#34;将结构放在自己的头文件中,并将它们包含在类头文件中。

您可以转发声明它们,但这需要更改矢量以使用指针。 (在这种情况下,我会建议std::vector<std::unique_ptr<trans>>)。如果结构庞大而复杂,这可能是合适的。

前向声明方法的主要优点是减少编译时间。但是,如果结构实际上非常简单,那么我不会在这里使用指针的额外开销。

相关问题