声明指针;类型和名称之间的空格左边还是右边

时间:2023-03-22
本文介绍了声明指针;类型和名称之间的空格左边还是右边的星号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
什么更有意义 - char* string 或 char *string?C++ 中的指针声明:星号的位置

我已经在很多代码中看到了这个的混合版本.(顺便说一下,这适用于 C 和 C++.)人们似乎以两种方式之一声明指针,我不知道哪一种是正确的,甚至不知道是否重要.

I've seen mixed versions of this in a lot of code. (This applies to C and C++, by the way.) People seem to declare pointers in one of two ways, and I have no idea which one is correct, of if it even matters.

将星号放在类型名称旁边的第一种方法,如下所示:

The first way it to put the asterisk adjacent the type name, like so:

someType* somePtr;

第二种方法是将星号放在变量名称旁边,如下所示:

The second way is to put the asterisk adjacent the name of the variable, like so:

someType *somePtr;

这让我发疯有一段时间了.是否有任何标准的方法来声明指针?指针的声明方式是否重要?我之前使用过这两个声明,我知道编译器并不关心它是哪种方式.然而,我已经看到以两种不同方式声明的指针这一事实让我相信这背后是有原因的.我很好奇这两种方法是否以某种我缺少的方式更具可读性或逻辑性.

This has been driving me nuts for some time now. Is there any standard way of declaring pointers? Does it even matter how pointers are declared? I've used both declarations before, and I know that the compiler doesn't care which way it is. However, the fact that I've seen pointers declared in two different ways leads me to believe that there's a reason behind it. I'm curious if either method is more readable or logical in some way that I'm missing.

推荐答案

这是一个偏好问题,有点像大括号样式.

It's a matter of preference, and somewhat of a holy war, just like brace style.

风格

someType* somePtr;

强调指针变量的类型.它本质上是说,somePtr 的类型是指向someType 的指针".

is emphasizing the type of the pointer variable. It is saying, essentially, "the type of somePtr is pointer-to-someType".

风格

someType *somePtr

强调指向数据的类型.它本质上是说,somePtr 指向的数据类型是 someType".

is emphasizing the type of the pointed-to data. It is saying, essentially, "the type of data pointed to by somePtr is someType".

它们的意思是一样的,但这取决于给定程序员在创建指针时的心智模型是集中"在指向的数据还是指针变量上.

They both mean the same thing, but it depends on if a given programmer's mental model when creating a pointer is "focused", so to speak, on the pointed-to data or the pointer variable.

把它放在中间(如 someType * somePtr)是试图避免提交任何一个.

Putting it in the middle (as someType * somePtr) is trying to avoid committing to either one.

这篇关于声明指针;类型和名称之间的空格左边还是右边的星号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在 C++ 中通过指针传递比通过引用传递有好处吗 下一篇:NULL 与 nullptr(为什么被替换?)

相关文章

最新文章