[英]C++ error no match for 'operator:
I'm learning how to uses vectors and was writing a simple program that takes some information and puts it on a vector and then iterates it back. 我正在学习如何使用向量,并正在编写一个简单的程序,该程序会获取一些信息并将其放在向量上,然后对其进行迭代。 my source is
我的来源是
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;
}
and the error I get is: 我得到的错误是:
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'
can anyone help me locate the source of the problem please? 谁能帮助我找到问题的根源?
This: 这个:
*i->size
should be: 应该:
i->size
The ->
operator (which in your case is equal to (*i).size
) will automatically deference i
. ->
运算符(您的情况下等于(*i).size
)将自动引用i
。
you are getting that error because the compiler is trying to do: 您收到该错误,因为编译器正在尝试执行以下操作:
*(i->name)
Which is trying to dereference i->name
, and since i
is a pointer to the object with name
, it will fail. 这正在尝试取消引用
i->name
,并且由于i
是指向具有name
的对象的指针,因此它将失败。
Wheras what you want is: Wheras您想要的是:
(*i).name
or 要么
i->name
Which will dereference i
before trying to take name out of the structure. 在将名称从结构中取出之前,这将取消对
i
引用。
You should use either: 您应该使用以下任一方法:
i -> size
or 要么
(*i).size
but not the way you used. 但不是您惯用的方式。
try removing the "*" by changing 尝试通过更改删除“ *”
cout << "The name of the pet is " << *i->name << endl;
to 至
cout << "The name of the pet is " << i->name << endl;
or 要么
cout << "The name of the pet is " << (*i).name << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.