我正在编写一个程序,用C ++管理餐厅的产品,员工和账单。 但是编写函数从文件到Product结构读取产品信息时遇到问题。 这是C2280错误,它表示我的代码正试图引用已删除的函数。 我已经在Google中阅读了此错误,但了解得不多。 这是我的代码的摘录:
struct Product
{
string productID;
string productName;
string productType;
int productPrize; //USD
};
/* function to get Products information from file */
bool readProductInformation(ifstream f, ProductList& productList)
{
if (!f.is_open()) {
cout << "Can not onpen file for reading!" << endl;
return false;
}
f >> productList.numberOfProducts;
int amount = productList.numberOfProducts;
if (amount == 0) {
f.close();
return true;
}
PNode* temp = productList.head;
for (int i = 0; i < amount; i++)
{
string str;
getline(f, str, '\n');
stringstream iss(str);
getline(iss, temp->data.productID, '-');
getline(iss, temp->data.productName, '-');
getline(iss, temp->data.productType, '-');
f >> temp->data.productPrize;
temp->next = new PNode;
temp = temp->next;
}
temp = NULL;
f.close();
return true;
}
当我创建ifstream f
和productList list
并再次调用该函数时,就会出现错误!
答案 0 :(得分:2)
ifstream类型没有副本构造函数,因为它是有意删除的,这意味着您不能像在readProductInformation函数中那样按值传递它。可以在here中找到有关ifstream构造函数的更多信息,最重要的是以下内容
(3)复制构造函数(已删除) 已删除(无副本构造函数)。
为了解决此问题,只需按引用而不是按值传递ifstream对象。这意味着在函数中访问的对象实际上是传入的对象。对此对象所做的更改不限于函数内部。 Here是一篇不错的文章,其中详细介绍了区别。
因此您只需将其更改为
bool readProductInformation(ifstream& f, ProductList& productList)
为什么有人会故意删除副本构造函数?因为有时复制特定的对象没有意义,而且如果您没有专门删除对象的复制构造函数,则编译器很聪明,有时可以为您创建一个对象,让您执行意想不到的事情(复制)。 Here有点密集,但是很好地解释了删除和默认功能。