类和数组

Classes and Arrays

本文关键字:数组      更新时间:2023-10-16

我正在开发一个类,该类将获取员工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\emplyeetest.cpp(33):错误C2065:"num":未声明的标识符1> c:\users\nate\documents\visual studio 2010\projects\employeetest\emplyeetest.cpp(35):错误C2065:"num":未声明的标识符

第33&35是在第一代码块中指示的行I。

编辑:在进行了指示的更改后,我得到了以下输出:

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<lt;"按[ENTER]继续…"<lt;endl;cin.get();

cin >> i2[i].setid(num);

您编译的代码与显示的代码不同。此代码将产生编译错误,因为setid返回void,而num尚未声明。