【发布时间】:2018-03-08 21:40:28
【问题描述】:
大家好,我正在从事一个名为库存调查员的学校项目。规格如下:
到目前为止,我已经创建了一个类,其中包含一个结构和该结构的向量。 到目前为止,我所做的只是让类显示结构只是为了知道它可以工作,但是当我编译它并运行它时,什么也没有发生。这是代码。原谅我犯的任何菜鸟错误,我对课程和向量都很陌生。提前谢谢你!
//Inventory Inquisitor.cpp
#include <iostream>
#include <string>
#include <cctype> //for toupper
#include <fstream>
#include <vector>
using namespace std;
class Inventory
{
private:
struct item
{
string Description = " ";
double Quantity = 0;
double Wholesalescost = 0;
double Retailcost = 0;
string Dateadded = " ";
};
vector<item> Inv;
public:
void Display();
};
void Inventory::Display()
{
Inv[0].Description = "english";
Inv[0].Quantity = 1;
Inv[0].Wholesalescost = 100;
Inv[0].Retailcost = 200;
Inv[0].Dateadded = "3/8/2018";
cout << Inv[0].Description << endl;
cout << Inv[0].Quantity << endl;
cout << Inv[0].Wholesalescost << endl;
cout << Inv[0].Retailcost << endl;
cout << Inv[0].Dateadded << endl;
}
int main()
{
Inventory inst1;
inst1.Display();
}
【问题讨论】:
-
在
Display,Inv.size() == 0。您需要将item放入向量中。 -
第一次学习使用向量时,请将
vector_name[some_number]替换为vector_name.at(some_number)。 -
感谢您的建议,我似乎不明白您的意思,我用 vector_name.at(some_number) 替换了 vector_name[some_number],现在我收到一个错误,在抛出实例后调用终止of 'std::out_of_range' what(): vector::_M_range_check: __n(即 0)>= this->size()(即 0)
标签: c++ class object vector struct