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

标签 c++ struct include header header-files

我一直试图在 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"并开始使用该结构?

最佳答案

试试这个新来源:

学生.h

#include <iostream>

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

student.cpp

#include "student.h"

struct Student student;

关于C++,如何在头文件中声明结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2732978/

相关文章:

c++ - 如何使用 QGraphicsView 的缩放级别缩放 QGraphicsEllipseItem

C编程: Read from file and print on screen

c++ - 结构内存限制

c - 结构体指针在每次函数调用时都变为 NULL

php - 从包含的文件调用函数?

c++ - 为 g++ 永久添加包含路径和共享库

C 头文件 - 包含的正确方法

c++ - wxWidgets 和上下文菜单

c++ - 编写一个程序,读取一串字符并调用递归函数来确定字符串中的字母是否构成回文

c++ - 跨多个操作系统联网