我正在尝试用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;
}
};
答案 0 :(得分:5)
变量this
是指针,因此您需要使用this->first
来访问this
的成员。
所有指向结构的指针都是如此,您需要使用->
运算符而不是.
运算符。
您当然可以使用.
运算符,并且您非常接近,但指针解除引用运算符*
的{{3}}运算符低于.
运算符,因此您实际上尝试取消引用next
中的*point.next
元素。你需要像(*point).next
这样的括号。但是,使用->
运算符更容易,例如point->next
。