C ++에서 변수, 메서드 등에 대한 좋은 명명 규칙은 무엇입니까?
저는 Objective-C와 Cocoa 세계에서 왔는데, 많은 관습이 있고 많은 사람들이 그것이 당신의 코드를 아름답게 만든다고 말할 것입니다! 이제 C ++로 프로그래밍하는 경우 C ++ 용으로 이와 같은 좋은 문서를 찾을 수 없습니다.
표준 C ++에는 아마도 위와 같은 것이 없지만 다른 SDK 또는 API (Microsoft (?) 등) 규칙을 고수 할 수 있기를 바랍니다.
몇 가지 링크를 제공 할 수 있기를 바랍니다.
최소한의 일관되고 규칙을 어 기지 않는 한 원하는대로하세요 .
개인적으로 저는 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
그. (댓글에서 말했듯이 이름 지정 규칙만큼 중요하지 않은 경우가 아니면 코드에 Google 스타일 가이드를 채택 하지 마십시오 .)
개개인만큼이나 많은 명명 규칙이있을 것입니다. 어떤 중괄호 스타일을 사용할 지에 대한 논쟁은 끝이 없습니다 (그리고 무균).
그래서 두 가지 조언이 있습니다.
- 수 일관성있는 프로젝트 내
- 예약 된 식별자를 사용하지 마십시오 (두 개의 밑줄이 있거나 밑줄로 시작하여 대문자가 오는 모든 것).
나머지는 당신에게 달려 있습니다.
저는 실제로 Java 스타일을 자주 사용합니다. 유형 이름에는 PascalCase, 함수 및 변수에는 camelCase, 전 처리기 매크로에는 CAPITAL_WORDS를 사용합니다. 부스트 / STL 규칙보다 선호하는 이유는 _type
. 예
Size size();
대신에
size_type size(); // I don't like suffixes
이것은 StackOverflow 코드 포맷터 Size
가 유형 이름으로 인식하는 추가 이점이 있습니다 ;-)
이 페이지에 나열된 지침을 따릅니다. C ++ 프로그래밍 스타일 지침
또한 이 주제에 대한 매우 훌륭한 책인 Misfeldt et al의 The Elements of C ++ Style 을 읽어 보는 것이 좋습니다 .
C ++의 원저자 인 Bjarne Stroustrup은 자신이 좋아하는 스타일을 가지고 있습니다. http://www.stroustrup.com/bs_faq2.html
많은 사람들이 다소 엄격한 헝가리 표기법 변형 ( 무섭다 !) 을 제안 할 것이지만 , 이름 지정 제안에 대해서는 Google C ++ 코딩 지침을 살펴 보시기 바랍니다 . 이것은 가장 인기있는 명명 규칙은 아니지만 적어도 상당히 완전합니다. 사운드 명명 규칙 외에도 유용한 지침이 있지만 그 중 많은 부분을 염두에 두어야합니다 (예를 들어 예외 금지 및 최신 C ++ 코딩 스타일을 멀리하려는 경향).
개인적으로 나는 STL과 Boost의 극도로 낮은 기술의 컨벤션 스타일을 좋아하지만;).
일관성과 가독성 (자체 문서화 코드)이 중요합니다. 일부 단서 (예 : 케이스)는 충돌을 방지하고 인스턴스가 필요한지 여부를 표시하는 데 사용할 수 있으며 사용해야합니다.
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_ */
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.
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.
not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe
'program story' 카테고리의 다른 글
중첩 클래스 멤버에 대한 액세스를 포함 클래스로 제한하는 방법은 무엇입니까? (0) | 2020.12.14 |
---|---|
현재 실행중인 자바 스크립트 코드의 파일 경로를 얻는 방법 (0) | 2020.12.14 |
Rails 3 respond_to : 기본 형식? (0) | 2020.12.14 |
크롬 확장 프로그램의 현재 탭 URL을 어떻게 얻을 수 있습니까? (0) | 2020.12.14 |
사용자 등록시 정의되지 않은 지역 변수 또는 메소드`unconfirmed_email '? (0) | 2020.12.14 |