gpt4 book ai didi

c++ - 未在此范围内声明

转载 作者:太空宇宙 更新时间:2023-11-03 10:29:28 24 4
gpt4 key购买 nike

http://pastebin.com/4gvcQm7P

#include <iostream>

using namespace std;

int GenerateID()
{
static int nextID = 0;
return nextID++;
}

void PrintInformation(Employee EmployeeName)
{
cout << EmployeeName << "'s ID is: " << EmployeeName.ID << endl;
cout << EmployeeName << "'s age is: " << EmployeeName.age << endl;
cout << EmployeeName << "'s wage is: " << EmployeeName.wage << endl;
}

int main()
{

struct Employee
{
int ID;
int age;
float wage;
};

Employee Dominic;
Employee Jeffrey;

Dominic.ID = GenerateID();
Dominic.age = 22;
Dominic.wage = 7.10;

Jeffrey.ID = GenerateID();
Jeffrey.age = 28;
Dominic.wage = 7.10;

PrintInformation(Dominic);
PrintInformation(Jeffrey);

return 0;
}

/*
C:\CBProjects\Practise\main.cpp|11|error: variable or field 'PrintInformation' declared void|
C:\CBProjects\Practise\main.cpp|11|error: 'Employee' was not declared in this scope|
C:\CBProjects\Practise\main.cpp||In function 'int main()':|
C:\CBProjects\Practise\main.cpp|39|error: 'PrintInformation' was not declared in this scope|
||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|
*/

上面的 pastebin 链接显示了我使用的代码和构建报告。根据这份报告,我试图转发声明结构而不包括成员,然后出现“不完整类型”错误。

解决方案是什么?

编辑:我正在使用 c++11

编辑 2:如果我尝试转发声明结构,包括成员,会发生以下情况:

http://pastebin.com/rrt4Yjes#

最佳答案

有两种解决方案:使 Employee 成为非本地类/结构或使 PrintInformation 成为模板。对于第一个解决方案,只需移动 Employee before PrintInformation。第二种解决方案是:

template< typename Employee >
void PrintInformation(const Employee& EmployeeName)
{
cout << " EmployeeName's ID is: " << EmployeeName.ID << endl;
cout << " EmployeeName's age is: " << EmployeeName.age << endl;
cout << " EmployeeName's wage is: " << EmployeeName.wage << endl;
}

请注意,在任何情况下,您都不希望 Employee 的拷贝只是为了打印一些信息,因此请将 PrintInformation 的参数设为常量引用,如上所示。

关于c++ - <insert name of struct> 未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21097523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com