为什么指针使用 - >代替 。? [英] Why do pointers use -> instead of .?

查看:144
本文介绍了为什么指针使用 - >代替 。?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复:

之间有区别。和。 ?

假设我有这样的结构:

struct movies
{
    string title;
    int year;
} my_movie, *ptrMovie;

现在我访问 my_movie code> my_movie.year = 1999;
现在访问指针我必须这样做: ptrMovie-> year = 1999;

Now I access my_movie like this: my_movie.year = 1999;
Now to access a pointer I must do this: ptrMovie->year = 1999;

为什么指针使用 - > 运算符,正常的数据类型使用运算符?是否有任何原因,他们不能使用运算符?

Why do pointers use the -> operator and normal data types use the . operator? Is there any reason they couldn't both use the . operator?

推荐答案

The。操作符访问结构的成员,并且只能对结构变量进行操作。
如果你想做一个指针,你首先需要解引用指针(使用 * )然后访问成员(使用)。像

The . operator accesses a member of a structure and can operate only on structure variables. If you want to do this to a pointer, you first need to dereference the pointer (using *) and then access the member (using .). Something like

(*ptrMovie).year = 1999

- > 运算符是对此的简写。

The -> operator is a shorthand for this.

这篇关于为什么指针使用 - >代替 。?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆