2009-11-28 21 views
1

我在这行的一个问题:常量,转换和通用阵列问题

const int* index = faceArray[f].vertices; 

const Vector3& A = vertexArray[index[0]]; 
const Vector3& B = vertexArray[index[1]]; 
const Vector3& C = vertexArray[index[2]]; 

faceNormal[f] = Vector3::Cross(B - A, C - A).Normalize(); 

当我尝试编译,我得到一个错误:

error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const MyArray<Data>' (or there is no acceptable conversion) 
with [Data=Vector3] 
c:\...\projects\haziarnyek\hazi\hazi.cpp(502): could be 'Vector3 &MyArray<Data>::operator [](const int &)' 
with [Data=Vector3] 
while trying to match the argument list '(const MyArray<Data>, int)' 
with [Data=Vector3] 

faceArray[f].vertices是一个int数组。

而且vertexArray是一个通用的数组,我写的,类似于:

class MyArray { 
public: 
    struct element { 
     Data data; 
     struct element* next; 
    }; 
    element* list; 
    element* last; 
    int size; 
    MyArray(){ 
     list = new element(); 
     list->next = NULL; 
     last = list; 
     size = 0; 
    } 
    MyArray(int size){ 
     this->size = size; 
     element = new element(); 
     element* p = list; 
     for(int i = 0; i < size; i++) { 
      p->next = new element(); 
      p = p->next; 
     } 
     p->next = NULL; 
     last = p; 
    } 
    MyArray(const MyArray& o){ 
     size = o.size; 
     element * p = o.list->next; 
     list = new element(); 
     element * p2 = list; 
     while (p) { 
      p2 = p2->next; 
      p2 = new element(); 
      p2->data = p->data; 
      p = p->next; 
     } 
     p2->next = NULL; 
     last = p2; 
    } 
    Data& operator[](const int& i){ 
     if (i > size-1) { 
      for (int j = 0; j < i-size+1; j++) Push(); 
      return last->data; 
     } 
     element* p = list->next; 
     for (int j = 0; j < i; i++) { 
      p = p->next; 
     } 
     return p->data; 
    } 
    void Push(const Data& d) { 
     last->next = new element(); 
     last = last->next; 
     last->next = NULL; 
     last->data = d; 
    } 
    void Push() { 
     last->next = new element(); 
     last = last->next; 
     last->next = NULL; 
    } 
    ~MyArray() { 
     element* p = list->next; 
     element* p2; 
     delete list; 
     for(;p;) { 
      p2 = p; 
      p = p->next; 
      delete p2; 
     } 
    } 
}; 
+0

除非你告诉我们faceNormal是如何定义的,否则我们可能无法帮到你。 – bmargulies 2009-11-28 14:55:06

+0

如果您可以方便人们为您提供帮助,那么您更有可能获得有用的答案。下一次,不要让我们这么读你的心思! '':-) – 2009-11-28 19:43:27

回答

1

我想你给了第一个片段的背景下类似于

void f(const MyArray<Vector3> &vertexArray) { 
    ... 
} 

这个错误是因为不为常量实例定义了一个operator[]

const Data& operator[] (int i) const { 
    ... 
} 
2

你应该定义operator []的const版本:你不会做,因为它需要的增长情况,所以您需要填写以下内容并把它添加到的一个

const x& operator[] (unsigned idx) const;