无法对存储在容器中的指针调用公共方法
奇怪的是,我在 C++ 中遇到以下代码的编译错误。
class A
{
public:
void sayHai()
{
cout << "\n Hai";
}
};
int main(int argc, char** argv)
{
vector< A* > vectorA;
vectorA.push_back(new A());
for (vector< A* >::iterator iter = vectorA.begin();
iter != vectorA.end();
++iter)
*iter->sayHai();
}
这里我将指向 A 类的指针存储在向量中。当我尝试调用公共方法时,出现以下编译错误。
VectorExample.cpp: In function 'int main(int, char**)':
VectorExample.cpp:30: error: request for member 'sayHai' in
'* iter.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator->
[with _Iterator = A**, _Container = std::vector<A*,
std::allocator<A*> >]()', which is of non-class type 'A*'
有人遇到过这样的情况吗?为什么这被视为编译错误?解决这个问题的必要方法应该是什么?
我使用 g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46) 编译了上面的内容
Strangely I am getting compilation error in C++ for the following code.
class A
{
public:
void sayHai()
{
cout << "\n Hai";
}
};
int main(int argc, char** argv)
{
vector< A* > vectorA;
vectorA.push_back(new A());
for (vector< A* >::iterator iter = vectorA.begin();
iter != vectorA.end();
++iter)
*iter->sayHai();
}
Here I am storing pointer to class A in a vector. And when I try to call a public method I am getting the following compilation error.
VectorExample.cpp: In function 'int main(int, char**)':
VectorExample.cpp:30: error: request for member 'sayHai' in
'* iter.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator->
[with _Iterator = A**, _Container = std::vector<A*,
std::allocator<A*> >]()', which is of non-class type 'A*'
Has anyone encountered such situation? Why this is treated as a compilation error? And what should be the necessary approach to resolve this problem?
I compiled the above using g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能只是运算符优先级。错误消息看起来像是试图调用迭代器的 sayHai 方法。因此,请这样做:
Probably just be operator precedence. The error message looks like its trying to call the sayHai method of the iterator. So do this instead:
此错误是由于运算符 * 的优先级低于运算符 -> 造成的。
线路
*iter->sayHai();
将被视为
*(iter->sayHai());
换句话说,你所写的相当于*( (*iter).sayHi() ) // iter->sayHi 等价于 (*iter).sayHi()
编译失败,因为 iter 类型中没有名为 sayHi 的成员。
相反,请将有问题的行替换为:
(*iter)->sayHai();
这将首先取消引用 iter,然后按预期对结果指针引用的对象调用 sayHi。
This error is due to the operator * having lower precedence than the operator ->.
The line
*iter->sayHai();
will be treated as
*(iter->sayHai());
In other words, what you have written is equivalent to*( (*iter).sayHi() ) // iter->sayHi equivalent to (*iter).sayHi()
This fails to compile because there is no member called sayHi in the type of iter.
Instead, replace the line in question with:
(*iter)->sayHai();
This will first dereference iter and then call sayHi as expected on the object referenced by the resulting pointer.