当在C ++中声明指针时,我在星号上放置星号吗? [英] Does it matter where I place the asterisk when declaring pointers in C++?

查看:115
本文介绍了当在C ++中声明指针时,我在星号上放置星号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习C ++,并从所有的示例代码,我看过在过去几天,我很难理解指针应该放在哪里。

I'm just learning C++ and from all the example code I have looked at over the past few days I am having a hard time understanding where the pointer should be placed.

这3个有什么区别?

1. char* x = /* ... */
2. char *y = /* ... */
3. char * z = /* ... */

1. ClassX* x = /* ... */
2. ClassY *y = /* ... */
3. ClassZ * z = /* ... */

感谢您的帮助。

推荐答案

没有区别。

您可以根据自己的喜好选择书写。通常,C ++程序员将星号放在类型旁边,而C程序员更常见的是将星号放在变量旁边。

You can choose to write it however you like. Typically, C++ programmers place the asterisk next to the type, while it is more common for C programmers to place the asterisk next to the name of the variable.

要注意的唯一缺陷是当你在一行上声明多个变量时(你真的不应该做,原因)。例如,在以下语句中,只有变量 x 被声明为指针:

The only pitfall to be aware of is when you declare multiple variables on a single line (which you really shouldn't do anyway, if not for precisely this reason). For example, in the following statement, only variable x is declared as a pointer:

char* x, y;

与以下内容进行比较,可以更清楚地知道哪些变量是指针:

Compare that with the following, which makes it much more clear which variables are pointers:

char *x, y;

最好的说法是,第三种语法在两个领先选项之间是一个不好的折衷。不是将星号放在一个或另一个旁边,有人决定将它放在中间,这是唯一确定不属于的地方。

As best I can tell, the third syntax emerged as a poor compromise between the two leading options. Instead of placing the asterisk next to one or the other, someone decided to place it in the middle, which is about the only place it decidedly does not belong.

这篇关于当在C ++中声明指针时,我在星号上放置星号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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