using getline gives error: no matching function for call to ‘getline(std::istream&, const string&)’

using getline gives error: no matching function for call to ‘getline(std::istream&, const string&)’

我正在编写这段代码,它与 cin>>partname; 一起工作,而不是在 showpart 函数中使用 getline(cin, partname);,但仅适用于不带空格的名称 space。但是使用 getline(cin, partname); 它会产生错误 error: no matching function for call to ‘getline(std::istream&, const string&)’

#include<iostream>
#include<cstring>

using namespace std;

class Inventory
{
  private:
    int partno;
    string partname;
    float cost;
    void getpart()
    {
      cout<<"Enter the part number"<<endl;
      cin>>partno;
      cout<<"Enter the part name"<<endl;
      cin>>partname;
      cout<<"Enter the cost"<<endl;
      cin>>cost;
    }

  public:
    Inventory()
    {
      partno = 0;
      partname = " ";
      cost = 0.0;
    }

    Inventory(int pn,string pname,float c)
    {
      partno = pn;
      partname = pname;
      cost = c;
    }

    void setpart()
    {
      getpart();
    }

    void showpart() const
    {
      cout<<"Inventory details"<<endl;
      cout<<"Part Number: "<<partno<<endl;
      cout<<"Part Name: ";
      getline(cin, partname);
      cout<<"\nCost: "<<cost<<endl;
    }
};

int main()
{
  Inventory I1(1,"Resistor", 25.0), I2;
  I2.setpart();
  I1.showpart();
  I2.showpart();
}

我已经查看过类似的错误,但它们似乎不是 helpful.Thank 你查看这个的原因。

#include <string> 而不是 <cstring>.

还有: void showpart() const 不能是 const 因为你更新了 partname (对于一个叫做 show-something 的函数来说这是一个奇怪的 activity)。

我怀疑您想要 显示 partname,而不是 更新 它:

void showpart() const
{
  cout<<"Inventory details"<<endl;
  cout<<"Part Number: "<<partno<<endl;
  cout<<"Part Name: "<<partname<<endl;
  cout<<"Cost: "<<cost<<endl;
}