2013-04-16 76 views
0

我正在學習如何使用向量,並正在編寫一個簡單的程序,它接收一些信息並將其放在一個向量上,然後迭代它。我的來源是C++錯誤不匹配'運算符:

int main() 
{ 

    int answer= 1; 
    int decide; 
    int vectCount = 0; 
    vector<animal> pet; 

    while(answer > 0) 
    {  

     pet.push_back(animal()); 
     cout << "enter the name of the pet" << endl; 
     getline(cin,pet[vectCount].name); 

      cout << "Please enter the age of the pet" << endl; 
      cin >> pet[vectCount].age; 

     cout << "enter the weight of the pet" << endl; 
     cin >> pet[vectCount].weight; 


     do 
     { 
     cout << "Please enter the size of the pet S/M/L" << endl; 
     cin >> pet[vectCount].size; 
     }while(pet[vectCount].size != 'L' 
     && pet[vectCount].size != 'M' 
     && pet[vectCount].size != 'S'); 

     answer = question(decide); 

    } 
    vector<animal>::iterator i; 
    for(i = pet.begin(); i != pet.end(); ++i) 
    { 

     cout << "The name of the pet is " << *i->name << endl; 
     cout << "The age of the pet is " << *i->age << endl; 
     cout << "The weight if the pet is " << *i->weight << endl; 
     cout << "The size of your pet is " << *i->size; 
     if(*i->size == 'S') 
     cout << "(-): meow" <<endl; 
     if(*i->size == 'M') 
     cout << "(---): woof" <<endl; 
     if(*i->size == 'L') 
     cout << "(------): moooo" <<endl;    
    } 
    cout << "Exiting the program" << endl; 


    cin.get(); 
    return 0; 
} 

,我得到的錯誤是:

no match for 'operator*' in '*(&i)->__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> [with _Iterator = animal*, _Container = std::vector<animal, std::allocator<animal> >]()->animal::name'

誰能幫我找到了問題的根源嗎?

+0

「問題之源」 - 讓我們開始由確定的行號編譯器。 –

回答

4

此:

*i->size 

應該是:

i->size 

->運營商(在你的情況是等於(*i).size)將自動尊重i

+0

工作。謝謝您的幫助 – user2284606

0

您獲得的錯誤,因爲編譯器要做的:

*(i->name) 

正試圖取消引用i->name,由於i是指向與name物體,它就會失敗。

Wheras你想要的是:

(*i).name 

i->name 

哪樣提領i試圖採取的名字在結構之前。

0

您應該使用:

i -> size 

(*i).size 

而不是你使用的方式。

0

嘗試 「*」 通過改變去除

cout << "The name of the pet is " << *i->name << endl; 

cout << "The name of the pet is " << i->name << endl; 

cout << "The name of the pet is " << (*i).name << endl;