Соглашения по стилю написания кода в Qt

http://qt.gitorious.org/, “QT Coding Conventions”, public translation into Russian from English More about this translation.

See also 6 similar translations

Translate into another language.

Participants

Uriel941 points
Ruzzz492 points
f-r-o-s-t345 points
And others...
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next
1 2 3 4 5

QT Coding Conventions

Соглашения по стилю написания кода в Qt

History of edits (Latest: Uriel 2 years, 9 months ago) §

C++ features

Особенности C++

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

Don’t use exceptions

Не используйте исключения

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

Don’t use rtti (Run-Time Type Information; that is, the typeinfo struct, the dynamic_cast or the typeid operators, including throwing exceptions)

Не используйте RTTI (RunTime Type Information) (Динамическую информацию о типах), а именно: структуру typeinfo, операторы dynamic_cast или typeid, который, помимо всего прочего, может возбудить исключение.

History of edits (Latest: Mashnin 1 year, 7 months ago) §

— Я бы сказал "(Динамическая информация о типах)" - в именительном падеже Reset

Use templates wisely, not just because you can.

Не стоит использовать шаблоны только потому, что у вас есть такая возможность. Используйте их с умом.

History of edits (Latest: Mashnin 1 year, 7 months ago) §

Hint: Use the compile autotest to see whether a C++ feature is supported by all compilers in the test farm.

Подсказка: Привыкайте делать автоматические тесты, чтобы проверять поддержку той или иной возможности языка на всей своей тестовой ферме (думаю, читающие люди будут в курсе, что это такое).

History of edits (Latest: Uriel 2 years, 9 months ago) §

Conventions in Qt source code

Соглашения в исходном коде Qt

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

All code is ascii only (7-bit characters only, run man ascii if unsure)

Весь код только в ASCII-кодировке (только 7-битные символы, читайте руководство по ASCII, если сомневаетесь)

History of edits (Latest: Reset 11 months, 4 weeks ago) §

Rationale: We have too many locales inhouse and an unhealthy mix of UTF-8 and latin1 systems. Usually, characters > 127 can be broken without you even knowing by clicking SAVE in your favourite editor.

Объяснение: Уж слишком много разных локальных кодировок существует в придачу к UTF-8 и Latin1. Да и вообще, символы с кодами больше 127 могут быть испорчены случайно, просто по нажатию «сохранить» в вашем любимом редакторе;

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

For strings: Use \nnn (where nnn is the octal representation of whatever locale you want your string in) or \xnn (where nn is hexadecimal). Example: QString s = QString::fromUtf8("\213\005");

Для строк: Используйте \nnn (где nnn — восьмеричное число, позволяющее задать символ в обобщённой нотации Unicode) или \xnn (где nn — шестнадцатиричное число). Например: QString s = QString::fromUtf8("\213\005");

History of edits (Latest: Uriel 2 years, 9 months ago) §

— локальной настройки - не нравится :) Ruzzz

For umlauts in documentation, or other non-ASCII characters, either use qdoc’s \unicode command or use the relevant macro; e.g. \uuml for ü

Для умляутов в документации или других не ASCII символов нужно использовать команду \unicode для qdoc или соответствующий макрос; например \uuml для символа «ü».

History of edits (Latest: Mashnin 1 year, 7 months ago) §

Every QObject subclass must have a Q_OBJECT macro, even if it doesn’t have signals or slots, otherwise qobject_cast will fail.

Каждый класс, производный от QObject должен иметь макрос Q_OBJECT, даже если не используются сигналы и слоты, иначе не будет выполняться qobject_cast.

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

Normalize the arguments for signals + slots (see QMetaObject::normalizedSignature) inside connect statements to get faster signal/slot lookups. You can use $QTDIR/util/normalize to normalize existing code.

Нормализованные аргументы в «связке» сигнал+слот (смотри QMetaObject:: normalizedSignature) внутри конструкции connect будут работать быстрее. Чтобы нормализовать существующий код, вы можете воспользоваться $QTDIR/util/normalize.

History of edits (Latest: Reset 11 months, 4 weeks ago) §

Including headers ##

Включение заголовочных файлов ##

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

In public header files, always use this form to include Qt headers: \#include <QtCore/qwhatever.h>. The library prefix is neccessary for Mac OS X frameworks and is very convenient for non-qmake projects.

При включении заголовочных файлов Qt, всегда используйте следующую форму записи: \#include <QtCore/qwhatever.h>. Префикс библиотеки необходим для фреймворков Mac OS X, а также очень целесообразен для не qmake проектов.

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

In source files, include specialized headers first, then generic headers.

В исходных кодах подключайте вначале специализированные заголовочные файлы, а затем уже общие.

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

— специализированные? Ruzzz

— А почему бы и нет. Вполне. :) Uriel

\#include <qstring.h> // Qt class

\#include <qstring.h> // класс Qt

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

\#include <new> // STL stuff

\#include <new> // файлы стандартной библиотеки C++

History of edits (Latest: Uriel 2 years, 9 months ago) §

\#include <limits.h> // system stuff

\#include <limits.h> // общесистемные файлы

History of edits (Latest: Uriel 2 years, 9 months ago) §

If you need to include qplatformdefs.h, always include it as the first header file.

Файл qplatformdefs.h необходимо всегда подключать первым.

History of edits (Latest: Reset 11 months, 4 weeks ago) §

If you need to include qt_x11_p.h, always include it as the last header file.

Если вам нужно подключить qt_x11_p.h, то подключайте его самым последним.

History of edits (Latest: Ruzzz 2 years, 9 months ago) §

Casting ##

Приведение типов ##

History of edits (Latest: Uriel 2 years, 9 months ago) §

Avoid C casts, prefer C++ casts (static_cast, const_cast, reinterpret_cast)

Вместо cast конструкций в стиле C используйте их С++-аналоги (static_cast, const_cast, reinterpret_cast).

History of edits (Latest: Uriel 2 years, 9 months ago) §

Rationale: Both reinterpret_cast and C-style casts are dangerous, but at least reinterpret_cast won’t remove the const modifier

Объяснение: Как приведение в стиле C, так и оператор reinterpret_cast являются опасными операциями, но второй при этом хотя бы учитывает константность переменной.

History of edits (Latest: Uriel 2 years, 9 months ago) §
Pages: ← previous Ctrl next
1 2 3 4 5