你最喜欢的C ++编码风格成语 [英] What are your favorite C++ Coding Style idioms

查看:161
本文介绍了你最喜欢的C ++编码风格成语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你最喜欢的C ++编码风格习语是什么?我问的是风格或编码排版,如放置花括号,在关键字后面有空格,缩进的大小等。这是反对最佳实践或要求,如总是删除数组 delete []

What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with delete[].

这是我最喜欢的一个例子:在C ++类初始化器中,我们将分隔符放在行的前面,而不是后面。这使得更容易保持这一最新。这也意味着源代码控制版本之间的差异更干净。

Here is an example of one of my favorites: In C++ Class initializers, we put the separators at the front of the line, rather than the back. This makes it easier to keep this up to date. It also means that source code control diffs between versions are cleaner.

TextFileProcessor::
TextFileProcessor( class ConstStringFinder& theConstStringFinder ) 

    : TextFileProcessor_Base( theConstStringFinder )

    , m_ThreadHandle  ( NULL )
    , m_startNLSearch (    0 )
    , m_endNLSearch   (    0 )
    , m_LineEndGetIdx (    0 )
    , m_LineEndPutIdx (    0 )
    , m_LineEnds      ( new const void*[ sc_LineEndSize ] )
{
    ;
}


推荐答案

创建枚举时,在命名空间中,以便您可以使用有意义的名称访问它们:

When creating enumerations, put them in a namespace so that you can access them with a meaningful name:

namespace EntityType {
    enum Enum {
        Ground = 0,
        Human,
        Aerial,
        Total
    };
}

void foo(EntityType::Enum entityType)
{
    if (entityType == EntityType::Ground) {
        /*code*/
    }
}

EDIT : ,这个技术在C ++ 11中已经过时了。 enum class enum struct 更加类型安全,简洁,灵活。对于旧式枚举,值将放在外部作用域中。使用新样式枚举,它们位于枚举类名称的范围内。

上一个示例使用scoped枚举重写(也称为强类型枚举):
):

EDIT: However, this technique has become obsolete in C++11. Scoped enumeration (declared with enum class or enum struct) should be used instead: it is more type-safe, concise, and flexible. With old-style enumerations the values are placed in the outer scope. With new-style enumeration they are placed within the scope of the enum class name.
Previous example rewritten using scoped enumeration (also known as strongly typed enumeration):

enum class EntityType {
    Ground = 0,
    Human,
    Aerial,
    Total
};

void foo(EntityType entityType)
{
    if (entityType == EntityType::Ground) {
        /*code*/
    }
}

使用作用域枚举还有其他显着的好处:缺少隐式转换, ,并且能够使用自定义底层类型(不是默认的 int )。

There are other significant benefits from using scoped enumerations: absence of implicit cast, possible forward declaration, and ability to use custom underlying type (not the default int).

这篇关于你最喜欢的C ++编码风格成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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