Qt技巧:Qt Coding Style

1830阅读 0评论2014-09-09 Jan5_Reyn
分类:C/C++

如果它使你的代码看起来不好,你可以打破任何一个规则 。

缩进

变量

// Wrong
int a, b;
char *c, *d;
 
// Correct
int height;
int width;
char *nameOfThis;
char *nameOfThat;
// Wrong
short Cntr;
char ITEM_DELIM = '/t';
 
// Correct
short counter;
char itemDelimiter = '/t';

补充

在Qt例子编写中,对变量名有如下建议:

void MyClass::setColor(const QColor &color;)
{
    this->color = color;
}

void MyClass::setColor(const QColor &newColor;)
{
    color = newColor;
}

避免使用 (意义不明确的字符):

void MyClass::setColor(const QColor &c)
{
    color = c;
}

注意:在构造函数中,会遇到同样的问题。但无论你信与不信,下面的可以工作

MyClass::MyClass(const QColor &color;)
    : color(color)
{
}

空白

// Wrong
if(foo){
}
 
// Correct
if (foo) {
}
char *x;
const QString &myString;
const char * const y = "hello";
// Wrong
char* blockOfMemory = (char* ) malloc(data.size());
 
// Correct
char *blockOfMemory = reinterpret_cast(malloc(data.size()));
//Wrong
x      = rect.x();
y      = rect.y();
width  = rect.width();
height = rect.height();

大括号

// Wrong
if (codec)
{
}
 
// Correct
if (codec) {
}
class Moo
{
};
// Wrong
if (address.isEmpty()) {
    return false;
}
 
// Correct
if (address.isEmpty())
    return false;

if (x) {
    // do something strange
    yyyyyyyyy = yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy +
                zzzzzzzzzzzzzzzzzzzzzz;
}
// Correct
if (address.isEmpty() || !isValid()
      || !codec) {
    return false;
}
// Wrong
if (address.isEmpty())
    return false;
else {
    qDebug("%s", qPrintable(address));
    ++it;
}
 
// Correct
if (address.isEmpty()) {
    return false;
} else {
    qDebug("%s", qPrintable(address));
    ++it;
}

// Wrong
if (a)
    if (b)
        ...
    else
        ...
 
// Correct
if (a) {
    if (b)
        ...
    else
        ...
}
// Wrong
while (a);
 
// Correct
while (a) {}

圆括号

// Wrong
if (a && b || c)
 
// Correct
if ((a && b) || c)
 
// Wrong
a + b & c
 
// Correct
(a + b) & c

switch语句

switch (myEnum) {
case Value1:
    doSomething();
    break;
case Value2:
    doSomethingElse();
    // fall through
default:
    defaultHandling();
    break;
}

断行

// Correct
if (longExpression
    + otherLongExpression
    + otherOtherLongExpression) {
}
//Wrong
if (dsfljfsfskjldsjkljklsjdk
    && fdsljsjdsdljklsjsjkdfs
    && dsfljkdfjkldksdfjdjkfdksfdkjld) {
    sadjdjddadhsad;
}

//Correct
if (dsfljfsfskjldsjkljklsjdk
        && fdsljsjdsdljklsjsjkdfs
        && dsfljkdfjkldksdfjdjkfdksfdkjld) {
    sadjdjddadhsad;
}

对 whle 或else if,不存在这个问题:

while (dsfljfsfskjldsjkljklsjdk
       && fdsljsjdsdljklsjsjkdfs
       && dsfljkdfjkldksdfjdjkfdksfdkjld) {
    sadjdjddadhsad;
}

补充

继承与virtual

上一篇:Qt技巧:Qt编程风格
下一篇:Qt技巧:Qt智能指针