使用链表c ++尝试类时出错

时间:2016-11-09 02:52:15

标签: c++ list iterator

我正在尝试简单的类和链表实现。 我收到这个代码请帮帮我 “列出迭代器不可解除” 在运行代码时。 感谢

#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;

}

2 个答案:

答案 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;
}