结构原型?

时间:2009-07-26 23:59:06

标签: c++ struct header structure

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

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

2 个答案:

答案 0 :(得分:6)

只需声明

struct person;

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

答案 1 :(得分:4)

如果您正在讨论结构声明:

person.h

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

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

如果您正在谈论结构的(全局)变量:

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文件。

相关问题