gpt4 book ai didi

c++ - 访问指针指向的值

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:22 26 4
gpt4 key购买 nike

编辑:这个问题应该被视为放弃。我已将此问题标记为删除,因为此时我什至不知道如何继续。我感谢你们所有人的愿意并抽出时间来帮助我。

我正在阅读并关注 cplusplus 上关于数据结构的文档。几个小时以来,我一直在试图弄清楚为什么编译器不接受“*pfruit.weight;”。可以肯定的是,我缺少的是一些简单的东西。

error C2228: left of '.weight' must have class/struct/union
1> type is 'product *'
1> did you intend to use '->' instead?

“句点 (.) 左侧的操作数不是类、结构或 union 。”

那么如何正确访问指针成员指向的值呢?(不是访问引用)

#include <iostream>

using namespace std;

struct product
{
int weight;
float price;
} ;

int main ()
{
product afruit;
product * pfruit;
pfruit = &afruit;

pfruit->weight;
//Access a member of an object to which we have a reference
//equivalent to: (*pfruit).weight

*pfruit.weight; //<------ I am so sorry, i meant This is the problem, i am using a reworded line of code from an example and it isn't compiling and returning the error.
//Access the value pointed by a pointer member called weight;
//equivalent to: *(pfruit.weight)

system("pause");
return 0;
}

最佳答案

这段代码

struct product
{
int weight;
float price;
} ;

int main ()
{
product * pfruit;

*pfruit.weight;

运算符优先级错误。 C++的规则是.的优先级高于**pfruit.weight 如果 pfruit 是一个结构并且 weight 是一个指针,那么 *pfruit.weight 是正确的,但在你的代码中它是相反的,pfruit 是指针,weight 只是一个整数。因此,您需要添加括号以正确地应用运算符

    (*pfruit).weight;

关于c++ - 访问指针指向的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16356453/

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