2016-11-09 63 views
0

我嘗試了簡單的類和鏈表實現。 請幫我用這段代碼,因爲我正在收到 「list iterator not derefereenable」 運行代碼時。 感謝嘗試類與鏈接列表時出錯C++

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

} 
+1

有沒有在你的列表中,這樣'curr'沒有指向一個有效的'Car',您需要將車添加到您的列表 – vu1p3n0x

+0

名爲'的getType()'setter是? –

回答

0

寫下面的方式

cout << "Please key in anything you want: "; 
getline(cin, p); 

c.push_back(Car()); 

list<Car>::iterator curr = c.begin(); 

curr->getType(p); 

它是更好的重命名成員函數getTypesetType。:)

要考慮到不帶參數的功能主要應應聲明爲

int main() 
^^^ 
0

您沒有在您的list中插入任何內容。所以迭代器是無效的,它指向c.end()並取消引用它是未定義的行爲。

在獲得begin迭代器之前,請在list中添加Car

#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; 
} 
相關問題