Qt 專案組通過挖掘 Qt 源碼、論壇討論、郵件列表及開發者協作,總結出這套編碼風格指南。遵循它能保證代碼風格一致、可讀性強、易於團隊協作與代碼審查。本文完整呈現核心規範,附帶正反例對比。
char *ptr;
const QString &ref;
const char * const constPtr = "text";
| 錯誤 | 正確 |
|---|---|
int a, b; | int height; |
short Cntr; | short counter; |
原則:左大括號與語句同行,**除函數定義與類定義外**。
// 正確
if (condition) {
doSomething();
}
// 錯誤
if (condition)
{
doSomething();
}
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() || !isValid()
|| !codec) {
return false;
}
// 錯誤
if (address.isEmpty())
return false;
else {
qDebug(...);
++it;
}
// 正確
if (address.isEmpty()) {
return false;
} else {
qDebug(...);
++it;
}
// 錯誤:else 屬於哪個 if?
if (a)
if (b)
...;
else
...;
// 正確:外層加大括號
if (a) {
if (b)
...;
else
...;
}
switch (myEnum) {
case Value1:
doSomething();
break;
case Value2:
doSomethingElse();
// fall through
default:
defaultHandling();
break;
}
// 正確
if (longExpression
+ otherLongExpression
+ otherOtherLongExpression) {
}
// 錯誤:行尾運算符易被窄編輯器截斷
if (longExpression +
otherLongExpression +
otherOtherLongExpression) {
}
// 錯誤
char *mem = (char *)malloc(size);
// 正確
char *mem = reinterpret_cast<char*>(malloc(size));
// 或更好:使用 new / 智能指針 / QByteArray / std::vector
如果規則讓代碼變醜,你可以打破它。
風格指南服務於可讀性與維護性,而非教條。在極少數情況下 (如高度優化的底層代碼、與第三方風格對接),靈活變通優於死守規則。
將此風格指南內化為肌肉記憶,並配合自動化工具強制執行,是打造高質量 Qt/C++ 代碼庫的基石。