[英]c++ Accessing members of objects using pointers
I have variable mode
, which I am declaring with the following line: 我有变量
mode
,我在下面的行中声明:
StatusRecord mode;
StatusRecord
is a struct
which holds several variables of different types. StatusRecord
是一个struct
,其中包含几个不同类型的变量。
I now want to create a pointer to mode
, and populate that pointer with some data by using a function to populate its attributes/ fields. 现在,我想创建一个指向
mode
的指针,并通过使用函数填充其属性/字段来向该指针填充一些数据。 I have tried doing this as follows: 我尝试这样做,如下所示:
StatusRecord mode;
StatusRecord *modePtr = &mode;
DataStore->getModeData(*modePtr);
Here, I am declaring the struct
variable, creating a pointer to it, and populating that pointer using the getModeData()
function. 在这里,我声明了
struct
变量,创建了一个指向它的指针,并使用getModeData()
函数填充了该指针。 However, I now want to use an attribute of the struct ptr
I've just populated in a conditional statement: 但是,我现在要使用我刚刚在条件语句中填充的
struct ptr
的属性:
if(*modePtr->eraseSelect ==2){
...
}
But I'm getting a compile error on this line that says: 但是我在这行上遇到了一个编译错误,它说:
Error: operand of '*' must be a pointer
错误:“ *”的操作数必须是指针
Does this mean that the eraseSelect
attribute should be a pointer as well as 'modePtr`? 这是否意味着
eraseSelect
属性应该是指针以及'modePtr`? How would I fix this error? 如何解决此错误?
Try this: 尝试这个:
if(modePtr->eraseSelect ==2){
...
}
or this: 或这个:
if((*modePtr).eraseSelect ==2){
...
}
So you can use "dot" syntax to reach fields of an instance or "arrow" syntax to reach fields of a pointer to the instance. 因此,您可以使用“点”语法到达实例的字段,或者使用“箭头”语法到达实例的指针的字段。 In most cases, "arrow" is more suitable.
在大多数情况下,“箭头”更为合适。
You dont need to dereference your pointer here: 您不需要在这里取消引用指针:
if(modePtr->eraseSelect ==2){
...
}
The issue is at *modePtr->eraseSelect
. 问题出在
*modePtr->eraseSelect
。
The ->
is used to access member variables of pointers to objects. ->
用于访问指向对象的指针的成员变量。 So, ptr->someMember
is equivalent to *(ptr).someMember
. 因此,
ptr->someMember
等效于*(ptr).someMember
。 You are mixing up the two, and so it doesn't make sense as you are dereferencing twice. 您将两者混为一谈,因此没有意义,因为您两次取消引用。
You should instead use modePtr->eraseSelect
instead. 您应该改为使用
modePtr->eraseSelect
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.