tags:

views:

129

answers:

2

I have a problem in these lines:

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();

When I try to compile, I get an error:

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 is an int array.

And vertexArray is a generic array that I wrote, similar to:

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;
        }
    }
};
+2  A: 

I take it the context of the first snippet you gave resembles

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

The error is because MyArray does not have an operator[] defined for constant instances. The one you have won't do because it grows instances as needed, so you'll need to fill in the following and add it to MyArray:

const Data& operator[] (int i) const {
    ...
}
Greg Bacon
+2  A: 

You should define a const version of operator[]:

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