简体   繁体   English

为什么不能指向指针,在没有强制转换的情况下访问结构成员?

[英]Why can't pointer to pointer, access struct members without a cast?

In C++, I was trying to access the struct members through double pointer headref as shown below在 C++ 中,我试图通过双指针headref访问结构成员,如下所示

struct Node{
    int data; 
    struct Node* next; 
};

struct Node* head = new Node;
head->data = 10; 
head->next = NULL; 

struct Node** headref = &head; 

However, accessing as *headref->data produces errors while casting it ((Node*)*headref)->data works.但是,作为*headref->data访问会在强制转换((Node*)*headref)->data时产生错误。 Why?为什么?

This expression这个表达

*headref->data

is equivalent to相当于

*( headref->data )

It is not the same as the valid expression它与有效表达式不同

( *headref )->data

because the data member data has no pointer type and you may not apply the unary operator * to it.因为数据成员data没有指针类型,您可能不会将一元运算符 * 应用于它。

This expression这个表达

((Node*)*headref)->data

is valid not due to the casting.有效不是由于铸造。 It is valid because if to remove the casting that is redundant you will get the valid edxpression这是有效的,因为如果删除多余的强制转换,您将获得有效的 edxpression

( /*(Node*)*/ *headref)->data

shown above.如上所示。

If you chain operators together, it's always a good idea to make sure you remember their precedence correctly.如果将运算符链接在一起,确保正确记住它们的优先级总是一个好主意。 As listed here , operator-> has a higher precedence than the indirection * .如此 所列, operator->的优先级高于间接* Hence因此

*headref->data

is interpreted as被解释为

*(headref->data)

which can't work.这是行不通的。 Instead, use相反,使用

(*headref)->data

which is equivalent to ((Node*)headref)->data .这相当于((Node*)headref)->data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么一个结构指针不能被另一个结构指针声明 - Why a struct pointer can't be declared by another struct pointer 为什么我们不能将 char 指针静态转换为 int 指针? - Why can't we static cast a char pointer to an int pointer? 是否未定义使用字符指针访问未填充结构的成员? - Is is undefined to access the members of an unpadded struct with a char pointer? C ++:通过指针访问struct的成员 - C++: Access members of struct via a pointer 我可以合法地将指向结构成员的指针转换为指向该结构的指针吗? - Can I legally cast a pointer to a struct member to a pointer to the struct? 将结构指针转换为双指针 - Cast struct pointer to double pointer 为什么不能在模板参数中向下转换指向成员的指针? - Why can't I downcast pointer to members in template arguments? 将指向struct的指针强制转换为指向该结构的唯一成员的指针 - Cast a pointer to struct to a pointer to the only member of that struct 为什么不能static_cast一个双void指针? - Why can't static_cast a double void pointer? 使用指向基本abstact类的指针访问子类成员,该类不能是dynamic_cast - Accessing child class members using pointer to a base abstact class, which can't be dynamic_cast
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM