gpt4 book ai didi

c++ - 请求*中的成员*,属于非类类型*

转载 作者:行者123 更新时间:2023-11-30 01:21:56 25 4
gpt4 key购买 nike

我试图在 C++ 中创建一个动态数组类,但我遇到了一些指针错误,例如。在第 23 行,我需要将 pointer 值(引用编号)更改为 this.first 的值,这也是一个指针 - pointerthis.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;
}
};

最佳答案

this 变量是一个指针,因此您需要使用this->first 来访问this< 的成员.

同样适用于所有指向结构的指针,您需要使用-> 运算符而不是. 运算符。

您当然可以使用 . 运算符,并且您非常接近,但是指针解引用运算符 * 具有较低的 precedence而不是 . 运算符,因此您实际上尝试取消引用 *point.next 中的 next 元素。您需要像 (*point).next 这样的括号。但是,使用 -> 运算符比 point->next 更容易。

关于c++ - 请求*中的成员*,属于非类类型*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com