gpt4 book ai didi

c++ - 类和数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:01 24 4
gpt4 key购买 nike

我正在开发一个类,该类将获取员工 ID 并付款,然后显示它。出现的问题是它没有标记任何错误,但它完全跳过了我应该输入数据的代码。

这就是我的代码的样子。

#include <iostream>
#include <iomanip>
using namespace std;

class employee
{
private:
int id;
float compensation;
public:
employee() : id(0), compensation(0)
{}
employee(int num, float pay) : id(num), compensation(pay)
{}
void setid(int i) { id=i; }
void setcomp(float comp) { compensation=comp; }
void displayinfo() { cout << "Id: " << id << endl << "Pay: " << compensation << endl; }
};

int main ( int argc, char* argv)
{
employee i1(1111, 8.25);
i1.displayinfo();

employee i2[3];
for (int i=0; i<3; i++)
{
cout << "Enter Employee ID: ";
cin >> i2[i].setid(num);
cout << "Enter Employee Pay: ";
cin >> i2[i].setcomp(num);
}

for(int i=0; i<3; i++)
{
i2[i].displayinfo();
}


//------------------------------------------------
system("Pause");
return 0;
}

最佳答案

这段代码甚至不应该编译。问题是你的循环:

employee i2[3];
for (int i=0; i<3; i++)
{
cout << "Enter Employee ID: ";
cin >> i2[i].setid(num); // Reading into a void return value.
cout << "Enter Employee Pay: ";
cin >> i2[i].setcomp(num); // Reading into a void return value.
}

您至少需要将其更改为:

employee i2[3];
for (int i=0; i<3; i++)
{
int num; float pay;
cout << "Enter Employee ID: ";
cin >> num;
i2[i].setid(num);
cout << "Enter Employee Pay: ";
cin >> pay;
i2[i].setcomp(pay);
}

注意:您的示例代码编译:

c:\users\nate\documents\visual studio 2010\projects\employeetest\employeetest\employeetest.cpp(33): error C2065: 'num' : undeclared identifier 1>c:\users\nate\documents\visual studio 2010\projects\employeetest\employeetest\employeetest.cpp(35): error C2065: 'num' : undeclared identifier

第 33 和 35 行是我在第一个代码块中指示的行。

编辑:进行指定更改后,我得到以下输出:

Id: 1111
Pay: 8.25
Enter Employee ID: 1
Enter Employee Pay: 1234.5
Enter Employee ID: 3
Enter Employee Pay: 5678.9
Enter Employee ID: 4
Enter Employee Pay: 123
Id: 1
Pay: 1234.5
Id: 3
Pay: 5678.9
Id: 4
Pay: 123
Press any key to continue . . .

另外,避免使用 system 函数。您可以在不产生另一个进程的情况下完成相同的操作(system 导致创建一个单独的进程),方法是: cout << "按 [ENTER] 继续..."<< endl; cin.get();

关于c++ - 类和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6104554/

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