指针列表 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19059057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pointer list c++
提问by user1519221
The code below:
下面的代码:
#include <iostream>
#include <list>
class A
{
public:
void printHello(){std::cout << "hello";}
};
int main(int argc, char *argv)
{
std::list<A*> lista;
lista.push_back(new A());
for(std::list<A*>::iterator it=lista.begin();it!=lista.end();++it)
{
//how to get to printHello method?
//it doesn't work
it->printHello();
}
return 0;
}
This code doesn't work. My question is how to get to method 'printHello' by iterator it? Thanks.
此代码不起作用。我的问题是如何通过迭代器获取方法“printHello”呢?谢谢。
回答by Daniel Frey
You want
你要
(*it)->printHello();
as the *it
returns the stored pointer A*
and only then you can apply ->
.
因为*it
返回存储的指针A*
,只有这样你才能申请->
。
回答by P0W
De-referencing it
will give you pointer to A, then you need to access the methods or data members.
取消引用it
将为您提供指向 A 的指针,然后您需要访问方法或数据成员。
So use :
所以使用:
(*it)->printHello();
(*it)->printHello();
回答by TASagent
Let me expand on Daniel's answer.
让我扩展丹尼尔的回答。
When you stick an asterisk in front of a variable, it is called 'dereferencing'. Used this way, the Asterisk is a 'Dereference Operator'. To put it noob-ishly (I don't know what level of understanding you have offhand), *pMyPointer
acts like it was the Object that the pMyPointer was pointing to. If it was a Pointer to a Pointer, then the result is just the Pointer.
当您在变量前添加星号时,它被称为“取消引用”。以这种方式使用,星号是一个“解引用运算符”。简单地说(我不知道你有什么水平的理解),*pMyPointer
就像 pMyPointer 指向的对象一样。如果它是一个指向指针的指针,那么结果就是指针。
As an example, when you call a method on a pointer, you use the Into Operator ->
.
例如,当您在指针上调用方法时,您使用 Into 运算符->
。
These two oftendo the same thing:
这两个经常做同样的事情:
pMyPointer->MyFunction();
pMyPointer->MyFunction();
(*pMyPointer).MyFunction();
(*pMyPointer).MyFunction();
In the case of the C++ iterators, the Dereference Operator is overwritten to return the object stored in its position. In this case, what is stored in its position is a pointer, so you still have to use ->
unless you stick another Dereference Operator in there.
在 C++ 迭代器的情况下,解引用运算符被覆盖以返回存储在其位置的对象。在这种情况下,它的位置存储的是一个指针,所以你仍然必须使用,->
除非你在那里插入另一个解引用运算符。
回答by villekulla
Just change following line
只需更改以下行
it->printHello();
to
到
(*it)->printHello();
The operator*() gives access to the contained data of the container, which in your case is a pointer. When not using pointers in containers, just using operator->() would work, too.
operator*() 可以访问容器中包含的数据,在您的情况下是指针。当不在容器中使用指针时,只使用 operator->() 也可以。