Const,转换和泛型数组问题

时间:2009-11-28 14:29:47

标签: c++ const

我在这些方面遇到了问题:

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;
        }
    }
};

2 个答案:

答案 0 :(得分:2)

您应该定义operator []的const版本:

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

答案 1 :(得分:1)

我把它给你的第一个片段的上下文类似

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

错误是因为MyArray没有为常量实例定义operator[]。你所拥有的那个不会因为它根据需要增长实例,所以你需要填写以下内容并将其添加到MyArray

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