指向结构体指针的成员访问语法
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是语法差异,差异的原因可以在 此处
由于通过指针访问结构体和类成员的语法很尴尬,因此 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.
基本上是一样的。但是,解引用运算符 (
*
) 和指针访问运算符 (->
) 都可以为类类型重载,因此可以为每个运算符提供不同的行为他们。然而,这是一个非常特殊的情况,而不是您的示例中的情况。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.