2009-11-28 33 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;