Читаем C++ Primer Plus полностью

ANSI has a downloadable PDF version available for $381. It can be ordered from the following website:

http://webstore.ansi.org

The ISO offers the document as a downloadable PDF file for CHF 352 or on a CD-ROM, also for CHF 352 (Swiss Francs), at the following site:

www.iso.org

Prices are subject to change.

• The C++ FAQ Lite site for frequently asked questions (in English, Chinese, French, Russian, and Portuguese) is a slimmed-down version of the book by Cline, et al. Currently it has the following URL:

• You can find a moderated discussion of C++ questions in the following newsgroup: comp.lang.C++.moderated.

• You can find information about specific C++ topics by using Google, Bing, and other search engines.

I. Converting to ISO Standard C++

You might have programs (or programming habits) that you developed in C or in older versions of C++ and you want to convert to standard C++. This appendix provides some guidelines. Some pertain to moving from C to C++, and others pertain to moving from older C++ to standard C++.

Use Alternatives for Some Preprocessor Directives

The C/C++ preprocessor provides an array of directives. In general, C++ practice is to use those directives that are designed to manage the compilation process and to avoid using directives as a substitute for code. For example, the #include directive is an essential component for managing program files. Other directives, such as #ifndef and #endif, let you control whether particular blocks of code get compiled. The #pragma directive lets you control compiler-specific compilation options. These are all useful, sometimes necessary, tools. You should exercise caution, however, when it comes to the #define directive.

Use const Instead of #define to Define Constants

Symbolic constants make code more readable and maintainable. The constant’s name indicates its meaning, and if you need to change the value, you just have to change the value once, in the definition, and then recompile. C uses the preprocessor to create symbolic names for a constant:

#define MAX_LENGTH 100

The preprocessor then does a text substitution in your source code, replacing occurrences of MAX_LENGTH with 100 prior to compilation.

The C++ approach is to apply the const modifier to a variable declaration:

const int MAX_LENGTH = 100;

This treats MAX_LENGTH as a read-only int.

There are several advantages to using the const approach. First, the declaration explicitly names the type. With #define, you must use various suffixes to a number to indicate types other than char, int, or double; for example, you use 100L to indicate a long type and 3.14F to indicate a float type. More importantly, the const approach can just as easily be used with compound types, as in this example:

const int base_vals[5] = {1000, 2000, 3500, 6000, 10000};

const string ans[3] = {"yes", "no", "maybe"};

Finally, const identifiers obey the same scope rules as variables. Thus, you can create constants with global scope, named namespace scope, and block scope. If, say, you define a constant in a particular function, you don’t have to worry about the definition conflicting with a global constant used elsewhere in a program. For example, consider the following:

#define n 5

const int dz = 12;

...

void fizzle()

{

    int n;

    int dz;

    ...

}

The preprocessor will replace

int n;

with

int 5;

and induce a compilation error. The dz defined in fizzle(), however, will be a local variable. Also if necessary, fizzle() can use the scope-resolution operator (::) and access the constant as ::dz.

C++ has borrowed the const keyword from C, but the C++ version is more useful. For example, the C++ version has internal linkage for external const values rather than the default external linkage used by variables and by the C const. This means that each file in a program using a const needs that const defined in that particular file. This might sound like extra work, but, in fact, it makes life easier. With internal linkage, you can place const definitions in a header file used by various files in a project. That is a compiler error for external linkage but not for internal linkage. Also because a const must be defined in the file that uses it (being in a header file used by that file satisfies the requirement), you can use const values as array size arguments:

const int MAX_LENGTH = 100;

...

double loads[MAX_LENGTH];

for (int i = 0; i < MAX_LENGTH; i++)

    loads[i] = 50;

This won’t work in C because the defining declaration for MAX_LENGTH could be in a separate file and not be available when this particular file is compiled. In fairness, it should be added that, in C, you could use the static modifier to create constants with internal linkage. It’s just that C++, by making static the default, requires one fewer thing for you to remember.

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных