简体   繁体   English

无法将列表迭代器强制转换为对象

[英]Cannot cast list iterator to an object

I get the error: 我收到错误:

error C2682: cannot use 'dynamic_cast' to convert from 'std::_List_iterator<_Mylist>' to 'UserBean *'

When executing: 执行时:

list<UserBean> * userBeans = getUserBeans();

for(list<UserBean>::iterator i = userBeans->begin(); i != userBeans->end(); i++)
   UserBean * newUser = dynamic_cast<UserBean*>(i);

Am I doing something wrong, or can you not convert iterator items to objects? 我做错了什么,或者你不能将迭代器项转换为对象?

Sometimes iterators are implemented as raw pointers to container items, but more times than not, they are not pointers at all, so don't treat them that way. 有时候迭代器被实现为容器项的原始指针,但更多时候它们根本就不是指针,所以不要那样对待它们。 The correct way to access the item that an iterator refers to is to dereference the iterator, eg: 访问迭代器引用的项的正确方法是取消引用迭代器,例如:

UserBean &newUser = *i;

Or: 要么:

UserBean *newUser = &(*i);

Iterators usually override the -> operator so you can access members of the referenced item, in cases where the iterator refers to an actual object instance (which yours does) and not a pointer to an object instance, eg: 迭代器通常会覆盖->运算符,因此您可以访问引用项的成员,如果迭代器引用实际的对象实例(您执行此操作)而不是指向对象实例的指针,例如:

i->SomeMemberHere

Am I doing something wrong, or can you not convert iterator items to objects? 我做错了什么,或者你不能将迭代器项转换为对象?

No, you can't. 不,你不能。 You can dereference iterators to access objects: 您可以取消引用迭代器来访问对象:

UserBean & newUser = *i;

You can't convert an iterator to a pointer like this - that's not what dynamic_cast is for. 你不能将迭代器转换为这样的指针 - 这不是dynamic_cast的用途。 You should only be using dynamic_cast when you're dealing with polymorphic behaviour (if at all). 在处理多态行为时(如果有的话),您应该只使用dynamic_cast You can, however, do it like so: 但是,您可以这样做:

UserBean* newUser = &*i;

This dereferences the iterator to get the object and then takes the address of the object. 这将取消引用迭代器以获取对象,然后获取对象的地址。

The type of your container is list<UserBean> not list<*UserBean> 容器的类型是list<UserBean> not list<*UserBean>

That's why your iterator is wrong. 这就是你的迭代器错误的原因。 Its type is UserBean . 它的类型是UserBean Not UserBean* . 不是UserBean*

UserBean userBean = *i;

or 要么

UserBean& userBean = *i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM