C++ 中的变量命名约定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/234866/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:56:51  来源:igfitidea点击:

Variable Naming Conventions in C++

c++variablesnaming-conventions

提问by stung

I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members.

我来自 .NET 世界,我是编写 C++ 的新手。我只是想知道在命名局部变量和结构成员时首选的命名约定是什么。

For example, the legacy code that I've inheritted has alot of these:

例如,我继承的遗留代码有很多:

struct MyStruct
{
   TCHAR           szMyChar[STRING_SIZE];
   bool            bMyBool;
   unsigned long   ulMyLong;
   void*           pMyPointer;
   MyObject**      ppMyObjects;
}

Coming from a C# background I was shocked to see the variables with hungarian notation (I couldn't stop laughing at the pp prefix the first time I saw it).

来自 C# 背景,我震惊地看到带有匈牙利符号的变量(我第一次看到它时忍不住笑了 pp 前缀)。

I would much rather name my variables this way instead (although I'm not sure if capitalizing the first letter is a good convention. I've seen other ways (see links below)):

我更愿意以这种方式命名我的变量(尽管我不确定第一个字母大写是否是一个好的约定。我见过其他方式(请参阅下面的链接)):

struct MyStruct
{
   TCHAR           MyChar[STRING_SIZE];
   bool            MyBool;
   unsigned long   MyLong;
   void*           MyPointer;
   MyObject**      MyObjects;
}

My question: Is this (the former way) still a preferred way to name variables in C++?

我的问题:这(前一种方式)仍然是在 C++ 中命名变量的首选方式吗?

References:

参考:

http://geosoft.no/development/cppstyle.html

http://geosoft.no/development/cppstyle.html

http://www.syntext.com/books/syntext-cpp-conventions.htm

http://www.syntext.com/books/syntext-cpp-conventions.htm

http://ootips.org/hungarian-notation.html

http://ootips.org/hungarian-notation.html

Thanks!

谢谢!

回答by Head Geek

That kind of Hungarian Notation is fairly useless, and possibly worse than useless if you have to change the type of something. (The properkind of Hungarian Notationis a different story.)

这种匈牙利表示法是相当无用的,如果您必须更改某些东西的类型,则可能比无用还要糟糕。(适当的那种匈牙利命名法的是一个不同的故事。)

I suggest you use whatever your group does. If you're the only person working on the program, name them whatever way makes the most sense to you.

我建议你使用你的团队所做的任何事情。如果您是该计划的唯一工作人员,请以对您最有意义的方式命名他们。

回答by Adam Rosenfield

The most important thing is to be consistent. If you're working with a legacy code base, name your variables and functions consistentlywith the naming convention of the legacy code. If you're writing new code that is only interfacing with old code, use your naming convention in the new code, but be consistent with yourself too.

最重要的是保持一致。如果您使用的是遗留代码库,请按照遗留代码的命名约定一致地命名变量和函数。如果您正在编写仅与旧代码交互的新代码,请在新代码中使用您的命名约定,但也要与您自己保持一致。

回答by peterchen

No. The "wrong hungarian notation" - especially the pp for double indirection - made some sense for early C compilers where you could write

不。“错误的匈牙利表示法”——尤其是双间接寻址的 pp——对早期的 C 编译器有一定的意义,你可以在那里编写

int * i = 17;
int j = ***i;

without even a warning from the compiler (and that might even be valid code on the right hardware...).

甚至没有来自编译器的警告(甚至可能是正确硬件上的有效代码......)。

The "true hungarian notation" (as linked by head Geek) is IMO still a valid option, but not necessarily preferred. A modern C++ application usually has dozens or hundreds of types, for which you won't find suitable prefixes.

“真正的匈牙利符号”(由 head Geek 链接)是 IMO 仍然是一个有效的选择,但不一定是首选。现代 C++ 应用程序通常有数十或数百种类型,您找不到合适的前缀。

I still use it locally in a few cases where I have to mix e.g. integer and float variables that have very similar or even identical names in the problem domain, e.g.

在某些情况下,我仍然在本地使用它,例如在问题域中必须混合具有非常相似甚至相同名称的整数和浮点变量,例如

float fXmin, fXmax, fXpeak; // x values of range and where y=max
int   iXmin, iXMax, iXpeak; // respective indices in x axis vector


However, when maintaining legacy code that does follow some conventions consistently (even if loosely), you should stick to the conventions used there - at least in the existing modules / compilation units to be maintained.

但是,在维护始终遵循某些约定(即使松散)的遗留代码时,您应该坚持那里使用的约定 - 至少在要维护的现有模块/编译单元中。

My reasoning: The purpose of coding standards is to comply with the principle of least surprise. Using one style consistently is more important than which style you use.

我的推理:编码标准的目的是遵守最小惊喜原则。始终如一地使用一种风格比使用哪种风格更重要。

回答by xyz

What's to dislike or mock about "ppMyObjects" in this example apart from it being somewhat ugly? I don't have strong opinions either way, but it does communicate useful information at a glance that "MyObjects" does not.

在这个例子中,除了有点难看之外,还有什么不喜欢或嘲笑“ppMyObjects”的?无论哪种方式,我都没有强烈的意见,但它确实一目了然地传达了“MyObjects”所没有的有用信息。

回答by Marcin

I agree with the other answers here. Either continue using the style that you are given from the handed down for consistency's sake, or come up with a new convention that works for your team. It's important that the team is in agreement, as it's almost guaranteed that you will be changing the same files. Having said that, some things that I found very intuitive in the past:

Class / struct member variables should stand out - I usually prefix them all with m_
Global variables should stand out - usuall prefix with g_
Variables in general should start with lower case
Function names in general should start with upper case
Macros and possibly enums should be all upper case
All names should describe what the function/variable does, and should never describe its type or value.

我同意这里的其他答案。要么继续使用传承下来的风格,以保持一致性,要么提出适合您团队的新约定。团队达成一致很重要,因为几乎可以保证您将更改相同的文件。话虽如此,我过去发现一些非常直观的事情:

类/结构成员变量应该突出 - 我通常用 m_ 前缀它们
全局变量应该突出 - 通常前缀 g_
变量通常应该以小写
函数开头名称一般应以大写
宏开头,可能枚举应全部大写
所有名称都应该描述函数/变量的作用,并且永远不应该描述它的类型或值。

回答by Nick

I'm a hungarian notation person myself, because I find that it lends readability to the code, and I much prefer self-documenting code to comments and lookups.

我自己是匈牙利符号的人,因为我发现它使代码具有可读性,而且我更喜欢自记录代码而不是注释和查找。

That said, I think you can make a case for sacrificing your preferred style and some additional maintainability for team unity. I don't buy the argument of consistency for the sake of uniform code readability, especially if your reducing readability for consistency... it just doesn't make sense. Getting along with the people you work with, though, might be worth a bit more confusion on types looking at variables.

也就是说,我认为你可以为团队团结牺牲你喜欢的风格和一些额外的可维护性。我不会为了统一的代码可读性而购买一致性的论点,特别是如果你为了一致性而降低可读性......这根本没有意义。但是,与与您一起工作的人相处可能值得对查看变量的类型进行更多的混淆。

回答by DavidG

Its all down to personal preference. I've worked for 2 companies both with similar schemes, where member vars are named as m_varName. I've never seen Hungarian notation in use at work, and really don't like it, but again down to preference. My general feel is that IDE's should take care of telling u what type it is, so as long as the name is descriptive enough of what it does ( m_color, m_shouldBeRenamed ), then thats ok. The other thing i do like is a difference between member variable, local var and constant naming, so its easy to see what is happening in a function and where the vars come from. Member: m_varName Const: c_varName local: varName

这完全取决于个人喜好。我曾为 2 家公司工作过,它们都有类似的方案,其中成员变量被命名为 m_varName。我从未见过在工作中使用匈牙利表示法,而且真的不喜欢它,但再次归结为偏好。我的总体感觉是 IDE 应该注意告诉你它是什么类型,所以只要名称足以描述它的作用( m_color, m_shouldBeRenamed ),那就可以了。我喜欢的另一件事是成员变量、局部变量和常量命名之间的区别,因此很容易看到函数中发生的事情以及变量的来源。成员:m_varName 常量:c_varName 本地:varName

回答by Leon Timmermans

Hungarian notation was common among users of the Win32 and MFC APIs. If your predecessors were using that, you can probably best continue using it (even though it sucks). The rest of the C++ world never had this brain-dead convention, so don't use it if you're using something other than those APIs.

匈牙利表示法在 Win32 和 MFC API 的用户中很常见。如果您的前任正在使用它,您最好继续使用它(即使它很糟糕)。C++ 世界的其余部分从未有过这种脑残的约定,因此如果您使用的不是这些 API,请不要使用它。

回答by Rob Prouse

I think that you will still find that most shops that program in Visual C++ stick with hungarian notation or at least a watered down version of it. In our shop, half of our app is legacy C++ with a shiny new C# layer on top (with a managed C++ layer in the middle.) Our C++ code continues to use hungarian notation but our C# code uses notation like you presented. I think it is ugly, but it is consistent.

我认为您仍然会发现大多数使用 Visual C++ 编程的商店都坚持使用匈牙利符号或至少是它的淡化版本。在我们的商店中,我们的应用程序的一半是遗留的 C++,顶部有一个闪亮的新 C# 层(中间有一个托管 C++ 层)。我们的 C++ 代码继续使用匈牙利表示法,但我们的 C# 代码使用您提供的表示法。我认为这很丑陋,但它是一致的。

I say, use whatever your team wants for your project. But if you are working on legacy code or joining a team, stick with the style that is present for consistency.

我说,使用您的团队想要的任何项目。但是,如果您正在处理遗留代码或加入团队,请坚持现有的风格以保持一致性。

回答by bkausbk

I also prefer CamelCase, indeed mostly I've seen people using CamelCase in C++. Personaly I don't use any prefixes expect for private/protected members and interfaces:

我也更喜欢 CamelCase,事实上我看到的大多数人在 C++ 中使用 CamelCase。我个人不使用任何前缀,除了私有/受保护的成员和接口:

class MyClass : public IMyInterface {
public:
    unsigned int PublicMember;
    MyClass() : PublicMember(1), _PrivateMember(0), _ProtectedMember(2) {}
    unsigned int PrivateMember() {
        return _PrivateMember * 1234; // some senseless calculation here
    }
protected:
    unsigned int _ProtectedMember;
private:
    unsigned int _PrivateMember;
};
// ...
MyClass My;
My.PublicMember = 12345678;

Why I decided to omit prefixes for public members:Because public members could be accessed directly like in structs and not clash with private names. Instead using underscores I've also seen people using first lower case letter for members.

为什么我决定省略公共成员的前缀:因为公共成员可以像在结构中一样直接访问,而不会与私有名称发生冲突。而不是使用下划线,我还看到人们使用第一个小写字母表示成员。

struct IMyInterface {
    virtual void MyVirtualMethod() = 0;
};

Interfaces contains per definition only pure virtual methods that needs to be implemented later. However in most situation I prefer abstract classes, but this is another story.

接口根据定义仅包含需要稍后实现的纯虚拟方法。然而,在大多数情况下,我更喜欢抽象类,但这是另一回事。

struct IMyInterfaceAsAbstract abstract {
    virtual void MyVirtualMethod() = 0;
    virtual void MyImplementedMethod() {}
    unsigned int EvenAnPublicMember;
};

See High Integrity C++ Coding Standard Manualfor some more inspiration.

有关更多灵感,请参阅高完整性 C++ 编码标准手册