类和数组
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尚未声明。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '