我正在尝试简单的类和链表实现。 我收到这个代码请帮帮我 “列出迭代器不可解除” 在运行代码时。 感谢
#include<iostream>
#include<list>
#include<string>
using namespace std;
class Car
{
public:
void getType(string x)
{
type = x;
}
string showType()
{
return type;
}
private:
string type;
};
void main()
{
string p;
list<Car> c;
list<Car>::iterator curr = c.begin();
cout << "Please key in anything you want: ";
getline(cin, p);
curr->getType(p);
cout << "The phrase you have typed is: " << curr->showType() << endl;
}
答案 0 :(得分:0)
写下面的方式
cout << "Please key in anything you want: ";
getline(cin, p);
c.push_back( Car() );
list<Car>::iterator curr = c.begin();
curr->getType(p);
将成员函数getType
重命名为setType
更好。:)
考虑到没有参数的函数main应声明为
int main()
^^^
答案 1 :(得分:0)
您没有在list
中插入任何内容。因此迭代器无效,它指向c.end()
并且取消引用它是未定义的行为。
而是在获得Car
迭代器之前向list
添加begin
。
#include<iostream>
#include<list>
#include<string>
using namespace std;
class Car
{
public:
void setType(const string& x)
{
type = x;
}
string showType()
{
return type;
}
private:
string type;
};
int main()
{
string p;
list<Car> c;
c.push_back(Car{});
auto curr = c.begin();
cout << "Please key in anything you want: ";
getline(cin, p);
curr->setType(p);
cout << "The phrase you have typed is: " << curr->showType() << endl;
}