C ++,如何在头文件中声明结构

问题描述 投票:22回答:7

我一直试图在student.h文件中包含一个名为“student”的结构,但我不太清楚该怎么做。

我的student.h文件代码完全由以下内容组成:

#include<string>
using namespace std;

struct Student;

student.cpp文件完全由以下内容组成:

#include<string>
using namespace std;

struct Student {
    string lastName, firstName;
    //long list of other strings... just strings though
};

不幸的是,使用#include "student.h"的文件会出现很多错误

error C2027: use of undefined type 'Student'

error C2079: 'newStudent' uses undefined struct 'Student'  (where newStudent is a function with a `Student` parameter)

error C2228: left of '.lastName' must have class/struct/union 

编译器(VC ++)似乎无法识别“student.h”中的struct Student?

如何在“student.h”中声明struct Student,以便我可以#include“student.h”并开始使用struct?

c++ struct include header header-files
7个回答
19
投票

你不应该在头文件中放置一个using指令,它会创建unnecessary headaches

你的标题中还需要一个include guard

编辑:当然,在修复了包含保护问题之后,您还需要在头文件中完整地声明学生。正如其他人所指出的那样,前瞻性声明在你的案件中是不够的。


26
投票

试试这个新来源:

student.h

#include <iostream>

struct Student {
    std::string lastName;
    std::string firstName;
};

student.cpp

#include "student.h"

struct Student student;

17
投票

您的student.h文件只向前声明一个名为“Student”的结构,它没有定义一个结构。如果您只通过引用或指针引用它,这就足够了。但是,只要您尝试使用它(包括创建一个),您将需要完整的结构定义。

简而言之,移动你的struct Student {...};进入.h文件并使用.cpp文件实现成员函数(它没有,所以你不需要.cpp文件)。


16
投票

C ++,如何在头文件中声明一个struct:

把它放在一个名为main.cpp的文件中:

#include <cstdlib>
#include <iostream>
#include "student.h"

using namespace std;    //Watchout for clashes between std and other libraries

int main(int argc, char** argv) {
    struct Student s1;
    s1.firstName = "fred"; s1.lastName = "flintstone";
    cout << s1.firstName << " " << s1.lastName << endl;
    return 0;
}

把它放在一个名为student.h的文件中

#ifndef STUDENT_H
#define STUDENT_H

#include<string>
struct Student {
    std::string lastName, firstName;
};

#endif

编译并运行它,它应该产生这个输出:

s1.firstName = "fred";

普罗蒂普:

您不应该在C ++头文件中放置using namespace std;指令,因为您可能会导致不同库之间的静默名称冲突。要解决此问题,请使用完全限定名称:std::string foobarstring;,而不是使用string foobarstring;包含std命名空间。


4
投票

您只在头文件中获得了student的前向声明;你需要将struct声明放在头文件中,而不是.cpp。方法定义将在.cpp中(假设您有)。


2
投票

好的,我注意到了三件大事

  1. 您需要在头文件中包含头文件
  2. 永远不要,在标题或类中放置一个using指令,而不是像std :: cout <<“say stuff”;
  3. 结构完全在头文件中定义,结构本质上是默认为public的类

希望这可以帮助!


1
投票

你不能。

为了“使用”结构,即能够声明该类型的对象并访问其内部,您需要结构的完整定义。因此,您想要执行任何操作(并且根据错误消息判断),您必须将结构类型的完整定义放入头文件中。

© www.soinside.com 2019 - 2024. All rights reserved.