【问题标题】:Structure prototype?结构原型?
【发布时间】:2010-11-14 05:30:15
【问题描述】:

如何将结构放在单独的文件中?我可以通过将函数原型放在头文件中来使用函数,例如file.h 和函数体在 file.cpp 之类的文件中,然后在带有 main 的源文件中使用包含指令 #include "file.h"。任何人都可以举一个简单的例子,用下面的结构做同样的事情吗?我正在使用 dev-c++。

struct person{
  string name;
  double age;
  bool sex;
};

【问题讨论】:

    标签: c++ struct header structure


    【解决方案1】:

    只要声明

    struct person;
    

    它被称为class forward declaration。在 C++ 中,结构体是所有成员默认为公共的类。

    【讨论】:

      【解决方案2】:

      如果您说的是结构声明:

      person.h

      #ifndef PERSON_H_
      #define PERSON_H_
      struct person{ 
        string name; 
        double age; 
        bool sex; 
      };
      #endif
      

      然后,您只需在需要该结构的 .cpp 文件中包含 person.h。

      如果您说的是结构的(全局)变量:

      person.h

      #ifndef PERSON_H_
      #define PERSON_H_
      struct person{ 
        string name; 
        double age; 
        bool sex; 
      };
      extern struct Person some_person;
      #endif
      

      一个 .cpp 文件中,您需要在全局范围内包含“some_person”定义的这一行

      struct Person some_person;
      

      现在每个需要访问全局“some_person”变量的 .cpp 文件都可以包含 person.h 文件。

      【讨论】:

      • 你的第一段代码是一个结构体定义,而不仅仅是一个结构体声明。
      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多