C++ 中变量、方法等的良好命名约定是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3706379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a good naming convention for vars, methods, etc in C++?
提问by nacho4d
I come from a the Objective-C and Cocoa world where there are lots of conventions and many people will say it makes your code beautiful! Now programming in C++ I cannot find a good document like this one for C++.
我来自 Objective-C 和 Cocoa 的世界,那里有很多约定,很多人会说它让你的代码变得漂亮!现在用 C++ 编程,我找不到像 C++ 这样的好文档。
Standard C++ probably does not have something like above but I hope I can stick to some other SDK or APIs (like Microsoft's(?),etc) conventions.
标准 C++ 可能没有像上面那样的东西,但我希望我可以坚持一些其他的 SDK 或 API(如 Microsoft 的(?)等)约定。
I hope you can provide me with some links.
我希望你能给我一些链接。
回答by GManNickG
Do whatever you want as long as its minimal, consistent, and doesn't break any rules.
做任何你想做的事情,只要它是最小的、一致的,并且不违反任何规则。
Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on m
and p
prefixes to members and parameters, respectively, giving:
就个人而言,我发现 Boost 风格最简单;它与标准库相匹配(使代码具有统一的外观)并且很简单。我个人分别为成员和参数添加前缀m
和p
前缀,分别给出:
#ifndef NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#define NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#include <boost/headers/go/first>
#include <boost/in_alphabetical/order>
#include <then_standard_headers>
#include <in_alphabetical_order>
#include "then/any/detail/headers"
#include "in/alphabetical/order"
#include "then/any/remaining/headers/in"
// (you'll never guess)
#include "alphabetical/order/duh"
#define NAMESPACE_NAMES_THEN_MACRO_NAME(pMacroNames) ARE_ALL_CAPS
namespace lowercase_identifers
{
class separated_by_underscores
{
public:
void because_underscores_are() const
{
volatile int mostLikeSpaces = 0; // but local names are condensed
while (!mostLikeSpaces)
single_statements(); // don't need braces
for (size_t i = 0; i < 100; ++i)
{
but_multiple(i);
statements_do();
}
}
const complex_type& value() const
{
return mValue; // no conflict with value here
}
void value(const complex_type& pValue)
{
mValue = pValue ; // or here
}
protected:
// the more public it is, the more important it is,
// so order: public on top, then protected then private
template <typename Template, typename Parameters>
void are_upper_camel_case()
{
// gman was here
}
private:
complex_type mValue;
};
}
#endif
That. (And like I've said in comments, do notadopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)
那。(就像我在评论中已经说过了,千万不能采用谷歌风格指南为您的代码,除非它是什么东西无关紧要的命名约定。)
回答by Matthieu M.
There are probably as many naming conventions as there are individuals, the debate being as endless (and sterile) as to which brace style to use and so forth.
命名约定可能与个人一样多,关于使用哪种支架样式等问题的争论是无休止的(而且毫无意义)。
So I'll have 2 advices:
所以我有两个建议:
- be consistentwithin a project
- don't use reserved identifiers (anything with two underscores or beginning with an underscore followed by an uppercase letter)
- 是一致的项目中
- 不要使用保留标识符(任何带有两个下划线或以下划线开头后跟大写字母的标识符)
The rest is up to you.
剩下的就看你了。
回答by Philipp
I actually often use Java style: PascalCase for type names, camelCase for functions and variables, CAPITAL_WORDS for preprocessor macros. I prefer that over the Boost/STL conventions because you don't have to suffix types with _type
. E.g.
我实际上经常使用 Java 风格:PascalCase 用于类型名称,camelCase 用于函数和变量,CAPITAL_WORDS 用于预处理器宏。我更喜欢 Boost/STL 约定,因为您不必在类型后缀_type
. 例如
Size size();
instead of
代替
size_type size(); // I don't like suffixes
This has the additional benefit that the StackOverflow code formatter recognizes Size
as a type name ;-)
这有一个额外的好处,即 StackOverflow 代码格式化程序将其识别Size
为类型名称;-)
回答by missingfaktor
We follow the guidelines listed on this page: C++ Programming Style Guidelines
我们遵循此页面上列出的指南:C++ 编程风格指南
I'd also recommend you read The Elements of C++ Style by Misfeldt et al, which is quite an excellent book on this topic.
我还建议您阅读Misfeldt 等人的 The Elements of C++ Style,这是一本关于这个主题的非常出色的书。
回答by Nemanja Trifunovic
For what it is worth, Bjarne Stroustrup, the original author of C++ has his own favorite style, described here: http://www.stroustrup.com/bs_faq2.html
值得一提的是,C++ 的原作者 Bjarne Stroustrup 有自己喜欢的风格,描述在这里:http: //www.stroustrup.com/bs_faq2.html
回答by Kornel Kisielewicz
While many people will suggest more or less strict Hungarian notationvariants (scary!), for naming suggestions I'd suggest you take a look at Google C++ Coding Guidelines. This may well be not the most popular naming conventions, but at least it's fairly complete. Apart from sound naming conventions, there's some useful guidelines there, however much of it should be taken with a grain of salt (exception ban for example, and the tendency to keep away from modern C++ coding style).
虽然许多人会建议或多或少严格的匈牙利符号变体(可怕!),但对于命名建议,我建议您查看Google C++ Coding Guidelines。这可能不是最流行的命名约定,但至少它相当完整。除了合理的命名约定之外,还有一些有用的指导方针,但其中的大部分内容都应该持保留态度(例如,禁止例外,以及远离现代 C++ 编码风格的趋势)。
Although personally I like the extreme low-tech convention style of STL and Boost ;).
虽然我个人喜欢 STL 和 Boost 的极低技术惯例风格;)。
回答by justin
consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.
一致性和可读性(自记录代码)很重要。一些线索(例如 case)可以而且应该用于避免冲突,并指示是否需要实例。
one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.
我进入的最佳实践之一是使用代码格式化程序(astyle 和 uncrustify 是 2 个示例)。代码格式化程序可以破坏您的代码格式化 - 配置格式化程序,让它完成它的工作。认真地,忘记手动格式化并开始使用它们。他们将节省大量时间。
as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.
如前所述,命名要非常具有描述性。此外,对范围(类类型/数据/命名空间/匿名命名空间)要非常具体。总的来说,我真的很喜欢 java 的很多常见的书面形式——这是一个很好的参考,类似于 c++。
as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):
至于具体的外观/命名,这是一个类似于我使用的小样本(变量/参数是lowerCamel,这仅展示了语言功能的一部分):
/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_
/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */
namespace NamespaceName {
/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
/* private types */
class t_thing {
/*...*/
};
public:
/* public types */
typedef uint64_t t_nanosecond;
/* factory initializers -- UpperCamel */
t_nanotimer* WithFloat(const float& arg);
/* public/protected class interface -- UpperCamel */
static float Uptime();
protected:
/* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
static const t_spoke Spoke;
public:
/* enums in interface are labeled as static class data */
enum { Granularity = 4 };
public:
/* construction/destruction -- always use proper initialization list */
explicit t_nanotimer(t_init);
explicit t_nanotimer(const float& arg);
virtual ~t_nanotimer();
/*
public and protected instance methods -- lowercaseCamel()
- booleans prefer is/has
- accessors use the form: getVariable() setVariable().
const-correctness is important
*/
const void* address() const;
virtual uint64_t hashCode() const;
protected:
/* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
virtual bool hasExpired() const;
private:
/* private methods and private static data */
void invalidate();
private:
/*
instance variables
- i tend to use underscore suffix, but d_ (for example) is another good alternative
- note redundancy in visibility
*/
t_thing ivar_;
private:
/* prohibited stuff */
explicit t_nanotimer();
explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */
回答by Alexander Rafferty
There are many different sytles/conventions that people use when coding C++. For example, some people prefer separating words using capitals (myVar or MyVar), or using underscores (my_var). Typically, variables that use underscores are in all lowercase (from my experience).
There is also a coding style called hungarian, which I believe is used by microsoft. I personally believe that it is a waste of time, but it may prove useful. This is were variable names are given short prefixes such as i, or f to hint the variables type. For example: int iVarname, char* strVarname.
人们在编写 C++ 代码时会使用许多不同的风格/约定。例如,有些人更喜欢使用大写字母(myVar 或 MyVar)或下划线(my_var)来分隔单词。通常,使用下划线的变量都是小写的(根据我的经验)。
还有一种叫做匈牙利语的编码风格,我相信微软使用了它。我个人认为这是浪费时间,但它可能证明是有用的。这是变量名被赋予短前缀如 i 或 f 来提示变量类型。例如:int iVarname、char* strVarname。
It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:
可以接受您以 _t 结束结构/类名称,以将其与变量名称区分开来。例如:
class cat_t {
...
};
cat_t myCat;
It is also generally accepted to add a affix to indicate pointers, such as pVariable or variable_p.
通常也接受添加词缀来指示指针,例如 pVariable 或 variable_p。
In all, there really isn't any single standard, but many. The choices you make about naming your variables doesn't matter, so long as it is understandable, and above all, consistent. Consistency, consistency, CONSISTENCY! (try typing that thrice!)
总之,真的没有任何单一的标准,而是很多。您在命名变量方面所做的选择并不重要,只要它是可以理解的,而且最重要的是一致。一致性,一致性,一致性!(尝试输入三次!)
And if all else fails, google it.
如果所有其他方法都失败了,请谷歌搜索。
回答by Goz
It really doesn't matter. Just make sure you name your variables and functions descriptively. Also be consistent.
真的没关系。只要确保以描述性的方式命名变量和函数即可。还要保持一致。
Nowt worse than seeing code like this:
现在比看到这样的代码更糟糕:
int anInt; // Great name for a variable there ...
int myVar = Func( anInt ); // And on this line a great name for a function and myVar
// lacks the consistency already, poorly, laid out!
Edit: As pointed out by my commenter that consistency needs to be maintained across an entire team. As such it doesn't matter WHAT method you chose, as long as that consistency is maintained. There is no right or wrong method, however. Every team I've worked in has had different ideas and I've adapted to those.
编辑:正如我的评论者所指出的,需要在整个团队中保持一致性。因此,您选择哪种方法并不重要,只要保持一致性即可。然而,没有正确或错误的方法。我工作过的每个团队都有不同的想法,我已经适应了这些想法。