【发布时间】:2011-05-22 10:19:29
【问题描述】:
我正在尝试将 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;
}
编译器正在输出:
main.cpp:在函数“int main()”中: main.cpp:19:错误:请求成员 ‘*’中的‘方法’ iterator.__gnu_cxx::__normal_iterator<_iterator _container>::operator-> with _Iterator = Interface**, _Container = std::vector >', 属于非类类型 ‘接口*’
知道我在这里做错了什么吗?
【问题讨论】:
-
“不工作”是什么意思?
-
编译失败,是的。我已经添加了 g++ 的输出。
标签: c++ interface vector iterator