C++ 中变量、方法等的良好命名约定是什么?

发布于 2024-09-18 15:32:22 字数 445 浏览 5 评论 0原文

我来自 Objective-C 和 Cocoa 的世界,那里有很多约定,很多人会说它让你的代码变得漂亮! 现在用 C++ 编程,我找不到像 C++ 这样的好文档。

http://developer.apple.com/library/ mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html

标准 C++ 可能没有类似上面的东西,但我希望我可以坚持一些其他 SDK 或 API(如 Microsoft 的(?)等)约定。

我希望你能为我提供一些链接。

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++.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html

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.

I hope you can provide me with some links.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

伊面 2024-09-25 15:32:22

做任何你想做的事,只要它最少,一致,并且 不违反任何规则

就我个人而言,我发现 Boost 风格最简单;它与标准库相匹配(使代码具有统一的外观)并且很简单。我个人分别在成员和参数上添加 mp 前缀,给出:

#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。
(就像我在评论中所说的那样,不要在您的代码中采用 Google 样式指南,除非它是为了像命名约定这样无关紧要的事情。)

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:

#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 not adopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)

躲猫猫 2024-09-25 15:32:22

有多少个人就有多少命名约定,关于使用哪种大括号样式等等的争论是无休止的(而且毫无结果)。

所以我有两个建议:

  • 在项目中保持一致
  • 不要使用保留标识符(任何带有两个下划线或以下划线开头后跟一个大写字母的标识符)

剩下的由你决定。

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 consistent within 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.

ゞ记忆︶ㄣ 2024-09-25 15:32:22

实际上,我经常使用 Java 风格:PascalCase 命名类型,camelCase 命名函数和变量,CAPITAL_WORDS 命名预处理器宏。与 Boost/STL 约定相比,我更喜欢这种方式,因为您不必使用 _type 为类型添加后缀。例如,

Size size();

而不是

size_type size();   // I don't like suffixes

This 的额外好处是 StackOverflow 代码格式化程序将 Size 识别为类型名称;-)

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.

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 ;-)

罗罗贝儿 2024-09-25 15:32:22

我们遵循本页列出的指南:C++ 编程风格指南


我还建议您阅读< a href="https://rads.stackoverflow.com/amzn/click/com/0521893089" rel="noreferrer">Misfeldt 等人的 The Elements of C++ Style,这是一本关于这方面的非常优秀的书话题。

We follow the guidelines listed on this page: C++ Programming Style Guidelines


I'd also recommend you read The Elements of C++ Style by Misfeldt et al, which is quite an excellent book on this topic.

够运 2024-09-25 15:32:22

无论如何,C++ 的原作者 Bjarne Stroustrup 有他自己最喜欢的风格,如下所述: http ://www.stroustrup.com/bs_faq2.html

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

孤蝉 2024-09-25 15:32:22

虽然许多人会建议或多或少严格的匈牙利表示法变体(可怕!),对于命名建议,我建议您查看 Google C++ 编码指南。这可能不是最流行的命名约定,但至少它相当完整。除了合理的命名约定之外,还有一些有用的指南,但其中大部分指南应持保留态度(例如,异常禁令,以及远离现代 C++ 编码风格的趋势)。

虽然我个人喜欢 STL 和 Boost 的极端低技术约定风格;)。

While many people will suggest more or less strict Hungarian notation variants (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).

Although personally I like the extreme low-tech convention style of STL and Boost ;).

醉梦枕江山 2024-09-25 15:32:22

人们在编写 C++ 代码时使用许多不同的风格/约定。例如,有些人喜欢使用大写字母(myVar 或 MyVar)或下划线(my_var)分隔单词。通常,使用下划线的变量都是小写的(根据我的经验)。
还有一种称为匈牙利语的编码风格,我相信微软也使用这种风格。我个人认为这是浪费时间,但可能会很有用。这是变量名被赋予短前缀(例如 i 或 f)来暗示变量类型。例如:int iVarname、char* strVarname。

人们普遍认为结构/类名称以 _t 结尾,以将其与变量名称区分开来。例如:

class cat_t {
  ...
};

cat_t myCat;

添加词缀来表示指针也是普遍接受的,例如pVariable或variable_p。

总而言之,实际上并没有单一的标准,而是有很多标准。您对变量命名所做的选择并不重要,只要它是可以理解的,并且最重要的是一致的。一致性,一致性,一致性! (尝试输入三次!)

如果所有其他方法都失败,请用谷歌搜索。

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.

It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:

class cat_t {
  ...
};

cat_t myCat;

It is also generally accepted to add a affix to indicate pointers, such as pVariable or 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.

影子的影子 2024-09-25 15:32:22

一致性和可读性(自文档代码)很重要。一些线索(例如大小写)可以而且应该用于避免冲突,并指示是否需要实例。

我采用的最佳实践之一是使用代码格式化程序(astyle 和 uncrustify 是两个例子)。代码格式化程序可能会破坏您的代码格式化 - 配置格式化程序,并让它完成其工作。说真的,忘记手动格式化并开始使用它们的实践。他们会节省大量时间。

如前所述,命名时应具有很强的描述性。另外,范围界定要非常具体(类类型/数据/命名空间/匿名命名空间)。总的来说,我真的很喜欢java的大部分常见书面形式——这是一个很好的参考,并且与c++类似。

至于具体的外观/命名,这是一个与我使用的类似的小样本(变量/参数是 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_ */

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.

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.

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++.

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):

/** 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_ */
溺渁∝ 2024-09-25 15:32:22

这真的没关系。只需确保以描述性方式命名变量和函数即可。还要保持一致。

现在没有比看到这样的代码更糟糕的了:

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! 

编辑:正如我的评论者所指出的,整个团队需要保持一致性。因此,只要保持一致性,您选择什么方法并不重要。然而,没有正确或错误的方法。我工作过的每个团队都有不同的想法,我已经适应了这些想法。

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.

坐在坟头思考人生 2024-09-25 15:32:22

不像您提供的链接那么简洁:但以下第 14 - 24 章可能会有所帮助:) 呵呵

参考: http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586/ref=sr_1_1?ie=UTF8&s=books&qid=1284443869&sr=8-1-猫科罗

not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe

ref: http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586/ref=sr_1_1?ie=UTF8&s=books&qid=1284443869&sr=8-1-catcorr

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文