2010-12-08 82 views
2

我想使用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*’

约我什么任何想法在这里做错了吗?

+0

“不工作”是什么意思? – kennytm 2010-12-08 19:05:34

+0

这是编译失败,是的。我已经添加了g ++的输出。 – 2010-12-08 19:07:26

回答

11

变化*iterator->method();(*iterator)->method();

前者解除引用iterator-的返回>()的方法。接口*没有方法(),它没有任何东西。

你想取消引用迭代器到达你的指针,然后取消引用它。

你已经基本上得到了与迭代器**相同的东西,所以相应地采取行动。

+3

详细说明:` - >`优先于`*`,与'2 * 2 + 2'中`*`相比,优先级高于'+'。 – Thanatos 2010-12-08 19:12:34

0

尝试(*iterator)->method();

0

没有什么对你做了什么,但创建原始指针的载体通常是一个坏主意本身无效,则应使用所有权强制执行指针(一种“智能”指针)一样的shared_ptr 。而且你也不需要去引用迭代器,它应该直接提供 - > method()。然而,我没有看到任何直接无法编译的代码,除了可能是你的*iterator->method(),因为上次我检查去引用的优先级非常低,你可能会做*(iterator->method())这是不可编译的。

+0

虽然关于让原始指针的向量在错误倾向性方面次优(与智能指针的向量相比)是正确的,但建议在不需要的情况下引用计数的智能指针是不酷的(并且sub - 效率最佳,但仍然不好)。有更好的解决方案:`boost :: ptr_vector`或像`unique_ptr`(C++ 0x)这样的智能指针的普通向量。 – Kos 2010-12-08 19:16:55

2

诺亚关于编译错误与迭代器+1,这是一个很好的解释。至于你以前的问题:

I'm a bit lost with what type to choose for the vector contents. Is this need to be a pointer ? do I have to make a "new Implementation()"?

是的,这必须是一个指针。原因很简单:类型T的向量只存储(并拥有)T类型的元素,而不是子类型 - 并且有充分的理由(如果子类具有不同的大小?)。

因此,您必须将对象存储在某处并将指针保留在向量中。事实上,通过operator new将它们存储在免费商店是最简单的选择。

如果你想让自己的生活更轻松一点,你可以使用boost::ptr_vector来达到你的目的。