Qt代码风格 [翻译]

2018-01-06  本文已影响92人  洞渊的自习室

缩进

变量声明

 // 错误
 int a, b;
 char *c, *d;

 // 正确
 int height;
 int width;
 char *nameOfThis;
 char *nameOfThat;
 // 错误
 short Cntr;
 char ITEM_DELIM = ' ';

 // 正确
 short counter;
 char itemDelimiter = ' ';

空格

 // 错误
 if(foo){
 }

 // 正确
 if (foo) {
 }
 char *x;
 const QString &myString;
 const char * const y = "hello";
 // 错误
 char* blockOfMemory = (char* ) malloc(data.size());

 // 正确
 char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
 // 错误
 if (foo) bar();

 // 正确
 if (foo)
     bar();

大括号

 // 错误
 if (codec)
 {
 }
 else
 {
 }

 // 正确
 if (codec) {
 } else {
 }
 static void foo(int g)
 {
     qDebug("foo: %i", g);
 }

 class Moo
 {
 };
 // 错误
 if (address.isEmpty()) {
     return false;
 }

 for (int i = 0; i < 10; ++i) {
     qDebug("%i", i);
 }

 // 正确
 if (address.isEmpty())
     return false;

 for (int i = 0; i < 10; ++i)
     qDebug("%i", i);
 // 正确
 if (address.isEmpty() || !isValid()
     || !codec) {
     return false;
 }
 // 错误
 if (address.isEmpty())
     qDebug("empty!");
 else {
     qDebug("%s", qPrintable(address));
     it;
 }

 // 正确
 if (address.isEmpty()) {
     qDebug("empty!");
 } else {
     qDebug("%s", qPrintable(address));
     it;
 }

 // 错误
 if (a)
     …
 else
     if (b)
         …

 // 正确
 if (a) {
     …
 } else {
     if (b)
         …
 }
 // 错误
 while (a);

 // 正确
 while (a) {}

小括号

 // 错误
 if (a && b || c)

 // 正确
 if ((a && b) || c)

 // 错误
 a + b & c

 // 正确
 (a + b) & c

switch语句

 switch (myEnum) {
 case Value1:
   doSomething();
   break;
 case Value2:
 case Value3:
   doSomethingElse();
   Q_FALLTHROUGH();
 default:
   defaultHandling();
   break;
 }

跳转语句 (break, continue, return, and goto)

 // 错误
 if (thisOrThat)
     return;
 else
     somethingElse();

 // 正确
 if (thisOrThat)
     return;
 somethingElse();

换行

 // 错误
 if (longExpression +
     otherLongExpression +
     otherOtherLongExpression) {
 }

 // 正确
 if (longExpression
     + otherLongExpression
     + otherOtherLongExpression) {
 }

一般例外

风格艺术

可以使用下面的代码风格使得你的代码更有艺术性

--style=kr 
--indent=spaces=4 
--align-pointer=name 
--align-reference=name 
--convert-tabs 
--attach-namespaces
--max-code-length=100 
--max-instatement-indent=120 
--pad-header
--pad-oper

请注意,“无限制”--max-instatement-indent仅用于astyle,因为如果后续行需要缩进限制,astyle不够智能以包装第一个参数。 鼓励您手动限制在语句缩进大约50个列:(原文:Note that "unlimited" --max-instatement-indent is used only because astyle is not smart enough to wrap the first argument if subsequent lines would need indentation limitation. You are encouraged to manually limit in-statement-indent to roughly 50 colums:)

    int foo = some_really_long_function_name(and_another_one_to_drive_the_point_home(
            first_argument, second_argument, third_arugment));

官方原文链接

上一篇 下一篇

猜你喜欢

热点阅读