指向结构体指针的成员访问语法

发布于 2024-09-04 00:44:20 字数 462 浏览 3 评论 0原文

#include <iostream>

typedef struct _person
{
    std::string name;
    unsigned int age;
}Person;

int main()
{
    Person *pMe = new Person;
    pMe->age = 10;
    pMe->name = "Larson";

    std::cout << "Me " << (*pMe).age << " " << (*pMe).name.c_str() << std::endl;

    return 0;
}

考虑上面的代码。可以通过两种方式引用结构的成员。例如,pMe->age(*pMe).age。这只是语法差异还是这两种方法有任何功能差异?

#include <iostream>

typedef struct _person
{
    std::string name;
    unsigned int age;
}Person;

int main()
{
    Person *pMe = new Person;
    pMe->age = 10;
    pMe->name = "Larson";

    std::cout << "Me " << (*pMe).age << " " << (*pMe).name.c_str() << std::endl;

    return 0;
}

Consider the above code. The members of the structures can be referenced in two ways. Eg., pMe->age or (*pMe).age. Is this just a syntactic difference or is there any functional difference available in these two approaches?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感性不性感 2024-09-11 00:44:20

这只是语法差异,差异的原因可以在 此处

由于通过指针访问结构体和类成员的语法很尴尬,因此 C++ 提供了第二个成员选择运算符 (->),用于从指针进行成员选择。因此两条线是等价的。
->运算符不仅更容易输入,而且更不容易出错,因为无需担心优先级问题。因此,当通过指针进行成员访问时,请始终使用 ->;操作员。

This is just a syntactic difference and the reason for the difference can be found here

Because the syntax for access to structs and class members through a pointer is awkward, C++ offers a second member selection operator (->) for doing member selection from pointers. Hence both lines are equivalent.
The -> operator is not only easier to type, but is also much less prone to error because there are no precedence issues to worry about. Consequently, when doing member access through a pointer, always use the -> operator.

ζ澈沫 2024-09-11 00:44:20

基本上是一样的。但是,解引用运算符 (*) 和指针访问运算符 (->) 都可以为类类型重载,因此可以为每个运算符提供不同的行为他们。然而,这是一个非常特殊的情况,而不是您的示例中的情况。

Basically it's the same. However, both the dereferencing operator (*) and the pointer access operator (->) could be overloaded for class types, so it's possible to supply different behaviour for each of them. That's a very special case however, and not the case in your sample.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文