我的代码中出现了这两个错误:
Error C3867 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str': non-standard syntax; use '&' to create a pointer to member 59
Error C2661 'Product::Product': no overloaded function takes 2 arguments 59
似乎当我尝试调用非默认构造函数时,即使我试图通过它,也只能得到2个参数4。这只是猜测,但我怀疑也许我需要添加一些NULL检查器或者其他的东西?但是我看不到我传递的任何参数都可能为NULL,所以我被卡住了。
这是我的非默认构造函数的声明和定义:
Product(bool restocking, string name, int quantity, double price); //Declaration
Product::Product(bool restocking, string name, int quantity, double price):InventoryItem(restocking), quantity_(quantity), price_(price) { } //Definition
产品是从InventoryItem
衍生的
这是麻烦的代码:
void InventorySystem::BuildInventory(void) {
int i{ 0 };
string name_buffer;
string quantity_buffer;
string price_buffer;
ifstream fin("in_inventory.txt");
if (fin) {
while (getline(fin, name_buffer, ';') && i < g_kMaxArray) {
getline(fin, quantity_buffer, ';');
getline(fin, price_buffer, '\n');
p_item_list_[i] = new Product(false, name_buffer, atoi(quantity_buffer.c_str), atof(price_buffer.c_str)); \\ Error on this line
i++;
item_count_++;
}
}
else {
cout << "Error: Failed to open input file." << endl;
}
fin.close();
}
答案 0 :(得分:0)
cstr()是一个函数,因此请确保调用它来获取结果(而不是将其视为成员变量)
p_item_list_[i] = new Product(false, name_buffer, atoi(quantity_buffer.c_str()), atof(price_buffer.c_str()));
答案 1 :(得分:0)
使用空括号调用不带参数的成员函数:
... atoi(quantity_buffer.c_str()) ...
如果编译器看到c_str
时没有括号,则它会做出非常不合理的假设,即您想使用指向它的指针来引用该函数本身。这是很少使用的功能。
要使问题更加复杂,指向成员函数的指针有两种可能的语法,其中之一是非标准的。这就是编译器所抱怨的。您不需要任何这些,因此请添加括号以告诉编译器您要调用该函数,而不要使用指向该函数的指针。
答案 2 :(得分:0)
对()
是function call operator。没有它,您只会得到功能指针,而不会进行呼叫
但是为什么应该避免使用atoi
?参见Why shouldn't I use atoi()。请改用stoi()
。并使用stod
来获取双精度值,而不是stof
来返回浮点数
p_item_list_[i] = new Product(false, name_buffer, stoi(quantity_buffer), stod(price_buffer));
如您所见,代码更加简洁,sto*
系列收到的std::string
比char*
还要好