为什么会出现“非标准语法;使用'&'创建指向成员的指针”和“没有重载函数需要2个参数”的错误?

时间:2019-10-27 23:55:29

标签: c++ syntax-error

我的代码中出现了这两个错误:

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();
}

3 个答案:

答案 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::stringchar*还要好