[英]Error overloading operator [] for a std vector object
I have a polygon class defined like this: 我有一个这样定义的多边形类:
#include <gVector3.h> // an array containing three floats (x,y,z coordinates)
#include <vector>
class Polygon {
private:
std::vector <gVector3> vertices;
std::vector <gVector3> color;
I overloaded the [] operator for this class like so 我像这样重载了此类的[]运算符
gVector3 Polygon::operator [](unsigned int i) const {
return vertices[i];
}
I've written a simple test case: 我编写了一个简单的测试用例:
gVector3 v1(0,0,1), v2(1,1,1), v3(2,0,1);
Polygon *p = new Polygon();
p->push(v1);
p->push(v2);
p->push(v3);
assert(p[0] == v1); // Assume == for the gVector3 class has been defined correctly
Push is defined like so.. 推的定义如下:
void Polygon::push(gVector3 vec){
this->vertices.push_back(vec);
}
Bottom line is that this assertion fails, and I'm not sure why. 最重要的是,这个断言失败了,我不确定为什么。 Perhaps I'm misusing the Vector classes indexing method?
也许我滥用了Vector类的索引方法?
Any insights would be helpful! 任何见解都会有所帮助!
p
is a pointer, so p[0]
is the Polygon
that it points to. p
是指针,所以p[0]
是它指向的Polygon
。 I'm surprised that it compiled; 我很惊讶它编译了; I guess there must be some strange implicit type conversion.
我猜肯定会有一些奇怪的隐式类型转换。
You almost certainly don't want to be messing around with pointers and new
: 您几乎可以肯定不希望被指针和
new
弄乱:
Polygon p;
p.push(v1);
p.push(v2);
p.push(v3);
assert(p[0] == v1);
but if you do for some reason, then you'll need to dereference the pointer before applying []
但是如果您出于某种原因这样做,则需要在应用
[]
之前取消引用指针
assert((*p)[0] == v1);
p[0]
is equivalent to *(p + 0)
, or just *p
, so its just giving you the Polygon
object you allocated. p[0]
等效于*(p + 0)
或*p
,因此它只是为您分配了Polygon
对象。 You aren't calling operator[]
on that object. 您没有在该对象上调用
operator[]
。 You need to do (*p)[0]
instead, which will first get you the Polygon
object and then call operator[]
on it. 您需要执行
(*p)[0]
,这将首先为您提供Polygon
对象, 然后在其上调用operator[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.