【发布时间】:2011-04-15 02:43:26
【问题描述】:
我阅读了另一篇文章,该文章回答了有关指针向量迭代器的问题。我试图在我的代码中使用相同的概念,但我收到了一些编译错误。我的代码基于的代码示例是:
vector<c*> cvect;
cvect.push_back(new sc);
vector<c*>::iterator citer;
for(citer=cvect.begin(); citer != cvect.end(); citer++) {
(*citer)->func();
}
我想使用类似的概念为具有两个数据成员的类创建一个深拷贝构造函数,这些数据成员是指向对象的指针向量。我的代码是这样的:
class MyContainer {
vector<MyStuff*> vecOne;
vector<MyStuff*> vecTwo;
public:
MyContainer(const MyContainer& other);
};
MyContainer::MyContainer(const MyContainer& other) {
// copy vector one
vector<MyStuff*>::iterator vec1_itr;
for (vec1_itr = other.vecOne.begin(); vec1_itr != other.vecOne.end(); vec1_itr++) {
vecOne.push_back(new MyStuff(vec1_itr));
}
// copy vector two
vector<MyStuff*>::iterator vec2_itr;
for (vec2_itr = other.vecTwo.begin(); vec2_itr != other.vecTwo.end(); vec2_itr++) {
vecTwo.push_back(new MyStuff(vec2_itr));
}
}
我收到一些编译错误,例如:
/path/MyContainer.cpp:38: 错误:'
vec1_Itr = other->MyContainer::vecOne. std::vector<_Tp, _Alloc>::begin [with _Tp = MyStuff*, _Alloc = std::allocator<MyStuff*>]()'中的'operator='不匹配候选人是:
__gnu_cxx::__normal_iterator<MyStuff*, std::vector<MyStuff, std::allocator<MyStuff> > >& __gnu_cxx::__normal_iterator<MyStuff*, std::vector<MyStuff, std::allocator<MyStuff> > >::operator=(const __gnu_cxx::__normal_iterator<MyStuff*, std::vector<MyStuff, std::allocator<MyStuff> > >&)
我也收到operator!= 的错误...而另一个向量的另一组相同的错误。
【问题讨论】:
-
您如何在
class MyContainer中声明vecOne和vecTwo? -
在旁注中,尝试使用
MyStuff复制构造函数,而不是向其传递迭代器。您可以将其称为...(new MyStuff(**vec1_itr)。这样会更简单 -
当心向量是否可以包含指向从
c派生的类型的对象的指针,这是合法的,因为您将切片它们。
标签: c++ pointers vector iterator