问题遇到的现象和发生背景
在复刻教科书案例时遇到的问题, 题目:
有一个结构体变量stu,内涵学生学号,姓名和三门课成绩, 在main函数中为各成员赋值, 在另一函数print中将它们的值输出.
首先定义结构体变量Student, 如果在main函数内定义, 程序报错; 在main函数外定义为全局变量, 程序正常
问题相关代码,请勿粘贴截图
include <iostream>
#include <cstring>
using namespace std;
int main()
{
struct Student
{
int num;
string name;
float score[3];
}stu={12345, "Li Fang", 67.5, 89, 78.5};
void print(Student*);
print(&stu);
return 0;
}
void print(Student* p)
{
cout<<p->num<<" "<<p->name<<" "<<p->score[0]<<" "<<p->score[1]<<" "<<p->score[2]<<endl;
}
运行结果及报错内容
test1.cpp: In function ‘int main()’:
test1.cpp:12:7: error: ‘void print(main()::Student*)’, declared using local type ‘main()::Student’, is used but never defined [-fpermissive]
12 | void print(Student*);
| ^~~~~
test1.cpp: At global scope:
test1.cpp:16:12: error: variable or field ‘print’ declared void
16 | void print(Student* p)
| ^~~~~~~
test1.cpp:16:12: error: ‘Student’ was not declared in this scope
test1.cpp:16:21: error: ‘p’ was not declared in this scope
16 | void print(Student* p)
| ^
test1.cpp:12:7: warning: ‘void print(main()::Student*)’ used but never defined
12 | void print(Student*);
| ^~~~~
我的解答思路和尝试过的方法
将结构体变量定义移至main函数外, 程序正常运行
#include <iostream>
#include <cstring>
using namespace std;
struct Student
{
int num;
string name;
float score[3];
}stu={12345, "Li Fang", 67.5, 89, 78.5};
int main()
{
void print(Student*);
print(&stu);
return 0;
}
void print(Student* p)
{
cout<<p->num<<" "<<p->name<<" "<<p->score[0]<<" "<<p->score[1]<<" "<<p->score[2]<<endl;
}
我想要达到的结果
如何在main函数内定义结构体变量且正常运行?