Chu*_*cky 0 c++ arrays parameters struct undefined
C++新手.只需制作一个简单的struct/array程序.为什么我不能像我打算在这里传递一系列结构?
int NumGrads();
int main()
{
struct Student {
int id;
bool isGrad;
};
const size_t size = 2;
Student s1, s2;
Student students[size] = { { 123, true },
{ 124, false } };
NumGrads(students, size);
std::cin.get();
return 0;
}
int NumGrads(Student Stu[], size_t size){
}
Run Code Online (Sandbox Code Playgroud)
我明白,它必须是事做与参考值或值传递,但肯定如果我在main()定义了它,我不应该得到一个错误与NumGrads的参数?
Ton*_*ion 12
你的结构是在你的内部定义的main,你的NumGrads函数是在你的外面定义的main.
这意味着您的结构定义在函数可以看到的范围之外.
移动上面结构的定义,您main的问题就解决了.
结构定义是本地的main.除了main你的NumGrads定义之外,没有任何东西可以看到它.在函数内部使用结构定义并不是很常见的事情 - 通常你会在命名空间范围内使用它.
您的NumGrads声明也不同意定义的参数类型.
// Define Student at namespace scope
struct Student {
int id;
bool isGrad;
};
int NumGrads(Student[], size_t); // The argument types are now correct
int main()
{
// ...
}
int NumGrads(Student Stu[], size_t size){
}
Run Code Online (Sandbox Code Playgroud)
Student定义于main().在main之外定义它,使其与以下内容相同NumGrads:
struct Student
{
int id;
bool isGrad;
};
int main()
{
...
}
Run Code Online (Sandbox Code Playgroud)