0

这可能是一个愚蠢的错误,但我收到以下错误:

    error: request for member ‘speak’ in ‘it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Bird* const*, _Container = std::vector<Bird*>, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = Bird* const&]()’, which is of non-class type ‘Bird* const’

导致错误的代码是:

void Aviary::speakAll(std::ostream &os) const{
for(std::vector<Bird*>::const_iterator it = birds.begin(); it != birds.end(); it++){
    it->speak(os);
}

}

我用来存储 Bird 指针的结构是:

typedef std::vector<Bird*> Birds;

void Aviary::addBird(Bird *bird){
if(!bird) throw std::logic_error("");
birds.push_back(bird);

}

问题是如何从指针调用对象成员函数?

4

1 回答 1

3

您正在迭代指针,而不是值。要引用迭代器指向的值,请使用->or *,您的值是一个指针,因此您需要第二次取消引用:

(*it)->speak(os);
// or
(**it).speak(os);

在这里,*it意思是给我指针,然后是第二个*取消引用指针->的意思。

于 2013-10-03T17:17:52.993 回答