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

Recall that the term Allocator is the template parameter name for an allocator class to manage memory. The term Allocator() is the default constructor for that class. Thus, the constructors, by default, use the default version of the allocator object, but they give you the option of using some other version of the allocator object. The following sections examine the constructors individually.

Default Constructor

This is the prototype for the default constructor:

explicit basic_string(const Allocator& a = Allocator());

Typically, you would accept the default argument for the allocator class and would use the constructor to create empty strings:

string bean;

wstring theory;

The following relationships hold after the default constructor is called:

• The data() method returns a non-null pointer to which 0 can be added.

• The size() method returns 0.

• The return value for capacity() is not specified.

Suppose you assign the value returned by data() to the pointer str. In this case, the first condition means str + 0 is valid.

Constructors That Use C-Style Strings

Constructors that use C-style strings let you initialize a string object from a C-style string; more generally, they let you initialize a charT specialization from an array of charT values:

basic_string(const charT* s, const Allocator& a = Allocator());

To determine how many characters to copy, the constructor applies the traits::length() method to the array pointed to by s. (The pointer s should not be a null pointer.) For example, the following statement initializes the toast object, using the indicated character string:

string toast("Here's looking at you, kid.");

The traits::length() method for type char uses the null character to determine how many characters to copy.

The following relationships hold after the constructor is called:

• The data() method returns a pointer to the first element of a copy of the array s.

• The size() method returns a value equal to traits::length().

• The capacity() method returns a value at least as large as size().

Constructors That Use Part of a C-Style String

Constructors that use part of a C-style string let you initialize a string object from part of a C-style string; more generally, they let you initialize a charT specialization from part of an array of charT values:

basic_string(const charT* s, size_type n, const Allocator& a = Allocator());

This constructor copies to the constructed object a total of n characters from the array pointed to by s. Note that it doesn’t stop copying if s has fewer characters than n. If n exceeds the length of s, the constructor interprets the contents of memory following the string as if they held data of type charT.

This constructor requires that s is not a null pointer and that n < npos. (Recall that npos is a static class constant equal to the maximum possible number of elements in a string.) If n equals npos, the constructor throws an out_of_range exception. (Because n is of type size_type and npos is the maximum size_type value, n cannot be greater than npos.) Otherwise, the following relationships hold after the constructor is called:

• The data() method returns a pointer to the first element of a copy of the array s.

• The size() method returns n.

• The capacity() method returns a value at least as large as size().

Constructors That Use an Lvalue Reference

The copy constructor looks like this:

basic_string(const basic_string& str);

It initializes a new string object using a string argument:

string mel("I'm ok!");

string ida(mel);

Here, ida would get a copy of the string managed by mel.

The next constructor additionally requires that you specify an allocator:

basic_string(const basic_string& str, const Allocator&);

The following relationships hold after either of these two constructors is called:

• The data() method returns a pointer to an allocated copy of the array whose first element is pointed to by str.data().

• The size() method returns the value of str.size().

• The capacity() method returns a value at least as large as size().

Moving along, the next constructor lets you set several items:

basic_string(const basic_string& str, size_type pos, size_type n = npos,

    const Allocator& a = Allocator());

The second argument pos specifies a location in the source string from which to begin the copying:

string att("Telephone home.");

string et(att, 4);

Position numbers begin with 0, so position 4 is the p character. Thus, et is initialized to "phone home.".

The optional third argument n specifies the maximum number of characters to copy. Thus, this initializes pt to the string "phone":

string att("Telephone home.");

string pt(att, 4, 5);

However, this constructor does not go past the end of the source string; for example, the following stops after copying the period:

string pt(att, 4, 200)

Thus, the constructor actually copies a number of characters equal to the lesser of n and str.size() - pos.

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

Все книги серии 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.

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

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