【发布时间】:2022-01-12 05:06:40
【问题描述】:
我的向量作为参数传入函数时遇到问题。我收到以下错误:
void checkout(std::vector<InvoiceItem,std::allocator<InvoiceItem>>)': cannot convert argument 1 from 'std::vector<InvoiceItem *,std::allocator<InvoiceItem *>>' to 'std::vector<InvoiceItem,std::allocator<InvoiceItem>>' classwork15 C:\Users\dhuan\source\repos\classwork15\classwork15\main.cpp
我调用了向量
vector<InvoiceItem*> order;
我在我的 main 中调用函数,在一个 while 循环中。
while (choice <= 4 && again == 'y')
{
if (choice == 1)
{
invoice = addToCart();
cart.append(invoice);
InvoiceItem* ptr = new InvoiceItem(invoice);
order.push_back(ptr);
}
else if (choice == 2)
{
cart.display();
}
else if (choice == 3)
{
checkout(order); // <-here
}
cout << "1: add to order, 2: view cart, 3: checkout" << endl;
cout << "Your choice: " << endl;
cin >> choice;
cout << endl;
}
这是函数,如果有帮助的话:
void checkout(vector<InvoiceItem*> order)
{
string name;
char again = 'y';
int orderNum = 1000;
double total;
cout << "Checking out" << endl;
cout << "Enter name: ";
cin >> name;
cout << endl;
cout << "INVOICE" << endl;
cout << "Order Number: " << orderNum++ << endl;
cout << "Customer: " << name << endl;
cout << endl;
cout << "QTY \tDescription \t\tEach \tSubtotal" << endl;
for (int i = 0; i < order.size(); i++)
{
cout << i + 1 << "\t" << order[i]->getDescription() << "\t\t" << order[i]->getPrice() << "\t" << order[i]->getTotal() << endl;
total += order[i]->getTotal();
}
cout << "Total Due: ";
cin >> total;
cout << endl;
}
【问题讨论】:
-
你从哪里调用这个函数?你传递给它什么类型的值?请发帖minimal reproducible example。
-
您的函数 definition 采用
vector<InvoiceItem*>,但错误声称该函数需要vector<InvoiceItem>,这意味着您的函数 声明是错误的,需要修复。 -
错误消息显示您正在尝试将
vector<InvoiceItem*>分配给vector<InvoiceItem>。事实上,它明确表示在main.cpp(您省略了行号)中声明了void checkout(vector<InvoiceItem>)——这与您问题中的定义不符。 -
对于这种情况,std::vector
可能是你需要的。阅读isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines,了解如何编写现代 C++(特别是 P.2。尽量避免新建/删除)