[C ++]将自定义类型(结构)传递给函数 [英] [C++] passing custom type (structure) to a function
问题描述
您好。我正在尝试这个,我发现了一些我无法理解的奇怪行为。
考虑这段代码:
Hi. I was experimenting with this and I found strange behaviour which I cant understand.
Consider this code:
#include "stdafx.h"
void passStructAsParam(Student s);
struct Student
{
int rollno;
char gender;
int age;
};
int main()
{
Student s;
s.rollno = 40;
s.gender = 'm';
s.age = 20;
passStructAsParam(s);
return 0;
}
void passStructAsParam(Student s)
{
printf("%d \n", s.rollno);
printf("%c \n", s.gender);
printf("%d \n", s.age);
}
此代码不起作用,因为结构是在函数声明后定义的,但是如果我这样做:
This code wont work because the structure is defined after the function declaration but if I do this:
#include "stdafx.h"
void passStructAsParam(struct Student s);
struct Student
{
int rollno;
char gender;
int age;
};
int main()
{
Student s;
s.rollno = 40;
s.gender = 'm';
s.age = 20;
passStructAsParam(s);
return 0;
}
void passStructAsParam(struct Student s)
{
printf("%d \n", s.rollno);
printf("%c \n", s.gender);
printf("%d \n", s.age);
}
这完全没问题。所以这里的问题是:为什么当我明确写出学生是函数参数列表中的结构时它可以工作但如果我不这样做?
我尝试了什么:
在CodeProject.com中提出问题
This works perfectly fine. So the question here is: Why when I explecitely write that the Student is a structure in the function's parameter list it works but if i dont it doesnt ?
What I have tried:
Asking question here in CodeProject.com
推荐答案
在函数声明中使用struct
关键字,你有一个所谓的前向声明:
When using thestruct
keyword in your function declaration you have a so called "forward declaration":
// Forward declaration
// Definition must be present later in this scope
struct Student;
// Can now use the forward declaration within other declarations
void passStructAsParam(Student s);
// Final definition of structure
struct Student
{
int rollno;
char gender;
int age;
};
我已将前向声明从函数声明中移出来解释发生了什么。
I have moved the forward declaration out of the function declaration to explain what is happening.
这篇关于[C ++]将自定义类型(结构)传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!