我想使用C++迭代器的接口,但没有设法使其工作。C++迭代器,接口和指针
我有点迷路了什么类型的矢量内容选择。这需要成为一个指针吗?我必须做出一个“新的实现()”吗?简而言之,我不清楚,而且我也找不到有用的例子。
这里是接口和实现(.h文件)。
class Interface{
public:
virtual int method() = 0;
};
class Implementation1 : public Interface{
public:
int method();
};
class Implementation2 : public Interface{
public:
int method();
};
.cpp文件:
#include "content.h"
int Implementation1::method(){
return 1;
}
int Implementation2::method(){
return 2;
}
而我的主要功能:
#include "content.h"
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
// create the vector and put elements in it
vector<Interface*> elements;
elements.push_back(new Implementation1());
elements.push_back(new Implementation1());
elements.push_back(new Implementation2());
// now iterate on them
vector<Interface*>::iterator iterator;
for(iterator = elements.begin(); iterator != elements.end(); ++iterator){
*iterator->method();
}
return 1;
}
的compilator的输出:
main.cpp: In function ‘int main()’: main.cpp:19: error: request for member ‘method’ in ‘* iterator.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> with _Iterator = Interface**, _Container = std::vector >’, which is of non-class type ‘Interface*’
约我什么任何想法在这里做错了吗?
“不工作”是什么意思? – kennytm 2010-12-08 19:05:34
这是编译失败,是的。我已经添加了g ++的输出。 – 2010-12-08 19:07:26