[英]Error Message: non-standard syntax; use '&' to create a pointer to member
[英]Why do I get “Non-standard syntax; use '&' to create pointer to member” and “no overloaded function takes 2 arguments” errors?
我的代码中出现这两个错误:
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 arguments。这只是猜测,但我怀疑也许我需要添加一些 NULL 跳棋或其他什么? 但我看不出我传递的任何 arguments 可能是 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();
}
cstr() 是一个 function,所以请确保调用它来获取结果(而不是将其视为成员变量)
p_item_list_[i] = new Product(false, name_buffer, atoi(quantity_buffer.c_str()), atof(price_buffer.c_str()));
使用空括号调用不带参数的成员 function:
... atoi(quantity_buffer.c_str()) ...
如果编译器看到没有括号的c_str
,它会做出一个非常不合理的假设,即您想使用指向它的指针来引用 function 本身。 这是一个很少使用的功能。
更复杂的是,指向成员 function 的指针有两种可能的语法,其中一种是非标准的。 这就是编译器所抱怨的。 您不需要任何这些,因此添加括号以告诉编译器您要调用 function 而不是指向它的指针。
对()
是function 调用运算符。 没有它,您只会得到function 指针,不会进行任何调用
但不要使用atoi()
。 看看应该避免的原因。 使用stoi()
代替,并使用stod()
获得双倍
p_item_list_[i] = new Product(false, name_buffer,
stoi(quantity_buffer), stod(price_buffer));
如您所见,代码更简洁,因为到处都没有.c_str()
,因为sto*
系列直接接收std::string
(这比接收const char*
好得多)
另一个注意事项:不要使用这么长的行。 没有人喜欢水平滚动
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.