1

我正在尝试在 C++ 中创建一个动态数组类,但我遇到了一些指针错误,例如。在第 23 行,我需要将pointer值(参考号)更改为 的值this.first,这也是一个指针 -pointer并且this.first应该指向相同的值。

#include <string>
#include <iostream>
using namespace std;

class ArrayMember {
    public:
        ArrayMember* next;
        ArrayMember* prev;
        int index;
        int value;
        ArrayMember(){}
};

class Array {
    private:
        ArrayMember* first;
        ArrayMember* last;
        int length;

    public:
        int get(int index){
        ArrayMember* point;

        if(index<length/2){
            point = this.first; //error: request for member ‘first’ in ‘this’, which is of non-class type ‘Array* const’
            while(*point.index != index) { // error: request for member ‘index’ in ‘point’, which is of non-class type ‘ArrayMember*’
                point = *point.next; //error: request for member ‘next’ in ‘point’, which is of non-class type ‘ArrayMember*’
            }
            return *point.value; //error: request for member ‘value’ in ‘point’, which is of non-class type ‘ArrayMember*’
        } else if(index<length) {
            point = this.last; //error: request for member ‘last’ in ‘this’, which is of non-class type ‘Array* const’
            while(*point.index != index){ //error: request for member ‘index’ in ‘point’, which is of non-class type ‘ArrayMember*’
                point = *point.prev; //error: request for member ‘prev’ in ‘point’, which is of non-class type ‘ArrayMember*’
            }
            return *point.value; //error: request for member ‘value’ in ‘point’, which is of non-class type ‘ArrayMember*’
        }else{
            return NULL; //warning: converting to non-pointer type ‘int’ from NULL
        }
    }
    int set(int index, int value){
        //...
    }
    int indexOf(int value){
        //...
    }
    Array(){
        ArrayMember x = new ArrayMember;
        x.index = 0;
        this.first = x;
        this.last = x;
    }
};
4

1 回答 1

5

该变量this是一个指针,因此您需要使用它this->first来访问this.

所有指向结构的指针也是如此,您需要使用->运算符而不是.运算符。

您当然可以使用.运算符,并且您非常接近,但指针取消引用运算符*优先级低于运算符.,因此您实际上尝试取消引用. 你需要像. 但是,使用运算符更容易,例如.next*point.next(*point).next->point->next

于 2013-06-25T18:38:22.373 回答