2016-11-09 7 views
0

シンプルなクラスとリンクリストの実装を試しています。 コードを実行しているときに "リストイテレータを参照できない" を受け取っているので、このコードで私を助けてください。 おかげリンクリストでクラスを試すときにエラーが発生しました。

#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'あなたは – vu1p3n0x

+0

あなたのリストに 'のgetType(という名前のセッターをカーを追加する必要があり、有効な' Car'を指していない 'ように、あなたのリストには何も')がありませんか? –

答えて

0

は次のよう

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

c.push_back(Car()); 

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

curr->getType(p); 

を書いて、setTypeにメンバ関数getTypeの名前を変更することがはるかに優れています。:)

をパラメータなしでことを考慮にmain関数を講じなければなりませんのように宣言する

int main() 
^^^ 
0

listに何も挿入していません。したがって、反復子は無効です。c.end()を指しており、逆参照は未定義の動作です。

代わりに、イテレータを取得する前に、listCarを追加してください。

#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; 
} 
関連する問題