这个结构是定义的,那么为什么函数认为它不是呢?
This struct is defined, so why does the function think it isn't?
C++新手。只是制作一个简单的结构/数组程序。为什么我不能像在这里一样传递一个结构数组?
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){
}
我理解这一定与传递引用或值有关,但如果我在main()中定义了它,那么NumGrads参数肯定不会出错?
您的结构在main
的内部被定义为,而NumGrads
函数在main
的外部被定义为。
这意味着你的结构是在你的函数可以看到它的范围之外定义的
将结构的定义移动到main
之上,问题就解决了。
Student
在main()
中定义。在main之外定义它,使其与NumGrads
:在同一范围内
struct Student
{
int id;
bool isGrad;
};
int 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){
}
struct Student
是在main内部声明的,因此int NumGrads
看不到它。此外,在main
中调用该函数时,该函数是未声明的。此时,唯一可用的声明是int NumGrads()
,这是一个不同的函数。
相关文章:
- C++:调用没有匹配函数:为什么需要一个空的构造函数?
- 我是C++新手,我想知道,为什么在c ++中使用纯虚函数?为什么要使用纯虚函数?
- 无法重新声明构造函数.为什么?
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 将指针传递给函数 - 为什么我无法打印地址?
- 我打算调用initializer_list构造函数,如果存在,则事先调用复制构造函数:为什么?
- C ++中的函数为什么我的编译器无法识别错误()
- 成员函数与友元函数:为什么是一个而不是另一个?
- 可怕的元函数:为什么它们更快?
- 调用自动构造函数:为什么我的类型不完整
- cpp 没有匹配的函数调用来调用构造函数.为什么
- POW函数为什么返回意外值
- 模板中的友元函数(为什么这在Visual Studio中失败,而不是GCC和Clang)
- 显式函数为什么
- C++构造函数初始化列表调用默认构造函数.为什么
- 未调用构造函数?为什么
- C++:自动向量重新分配调用复制构造函数?为什么
- C++ / 多态性 / 虚函数 / 为什么我的子类的函数没有被调用?
- Linux vs Windows std::map 赋值构造函数(为什么会有这样的区别?)
- 错误:使用已删除的函数.为什么?