【发布时间】:2020-06-12 00:46:15
【问题描述】:
所以我有 Sensor、Car 和 Agency 类,其中 Agency 类接受 Car 类,Car 类接受 Sensor 类。在我的 Agency 类的源文件中,我的 operator[]`\ 函数有一个错误,上面写着
error: invalid initialization of reference of type Agency& from expression of type Car
return *invtptr;
我的operator[] 函数应该是一种通过引用m_inventory 数据对象的方法来索引,它允许您访问代理机构的库存。
这是我的operator[] 函数:
Agency &Agency::operator[](int index) {
Car *invtptr = this->m_inventory;
if (index < 0 || index > 5) {
cout << "Array is out of bounds, exiting";
exit(0);
}
else {
for (int i = 0; i < index; i++) {
invtptr++;
}
}
return *invtptr;
}
这是我的汽车类头文件中的私有成员:
private:
char m_make[256], m_model[256], m_owner[256];
int m_year, m_sensoramnt;
Sensor m_sensor[3];
float m_baseprice, m_finalprice;
bool m_available;
下面是我的 Agency 类头文件中的私有成员:
private:
char m_name[256];
int m_zipcode[5];
Car m_inventory[5];
【问题讨论】:
-
无关建议:
else { return invtptr[index]; } -
值得一提的是,m_inventory 是一个包含 5 辆汽车的数组。如果 index 小于 0(良好)或大于 5,您将记录错误。这意味着您允许的值为 {0, 1, 2, 3, 4, 5}。 5虽然超出范围
-
关于
zipcode的注释。如果您使用char数组,您的生活会更轻松。您不必担心某些聪明人会为其中一个数字输入 40 亿。当然,您必须确保用户不是加拿大人并输入字母,但这就是isdigit的用途。由于zipcode是一串数字而不是一个诚实的数字,所以字符串更有意义。
标签: c++ pointers error-handling compiler-errors