类和数组

问题描述

| 我正在上一个班级,该班级需要一个员工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):错误C2065:\'num \':未声明的标识符   1> c:\\ users \\ nate \\ documents \\ Visual Studio 2010 \\ projects \\ employeetest \\ employeetest \\ employeetest.cpp(35):错误C2065:\'num \':未声明的标识符 第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 . . .
另外,请避免使用“ 4”功能。您可以通过执行以下操作而无需生成另一个进程(
system
会创建一个单独的进程)来完成此操作:     cout << \“按[ENTER]继续... \” << endl;     cin.get();     ,
cin >> i2[i].setid(num);
您正在编译与显示的代码不同的代码。此代码将产生编译错误,因为setid返回void并且尚未声明num。