C++类型铸造顺序/适当的代码格式?
可能重复:
Declaring pointers; asterisk on the left or right of the space between the type and name?
what is the difference between const int*, const int * const, int const *C++类型铸造顺序/适当的代码格式?
我一直在想,是什么样的区别:
float const &var
const float &var
以及其中之一是正确的方法编写代码? (包括上面的例子):
float const& var
float const &var
float const & var
,并用指针:
float * var
float *var
float* var
我始终把专用标志只在变量名称之前,感觉最符合逻辑的。那是正确的方法吗?
它们都同样有效。没有一个正确的方法;你应该做任何你发现最具可读性的东西(用于你自己的代码),或者遵循主流的风格(如果与他人合作)。
首先输入const
(例如,const float &
而不是float const &
)在我的经验中更为常见。
&
和*
的定位取决于程序员;根据我的经验,没有其他选择比任何其他选择更普遍。
关于你提到的第一个问题: 参见本: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.8
常量X & X和X常量& X是 等同。
当谈到指针:
float *var
是最好的方式。
原因是当你有多个指针变量时它不会给人错误的印象。
例如:
float *var, *foo, *bar;
是正确的,如果你想3个指针变量。
相比于可能错误代码:
float* var, foo, bar;
您所暴露的第一个代码片段提醒了const正确性:http://en.wikipedia.org/wiki/Const-correctness#C.2B.2B_syntax。 在其他两个代码片段中,任何变体都具有相同的效果。 有关指针和const关键字的更多信息,请参阅以下文档:http://www.cplusplus.com/doc/tutorial/pointers/
它。不。物。 – 2010-07-25 17:51:31
Duplicate:http://stackoverflow.com/questions/2660633/declaring-pointers-asterisk-on-the-left-or-right-of-the-space-between-the-type-a导致更多的重复。 – GManNickG 2010-07-25 17:55:03