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

Making the comparison functions friends facilitates comparisons between String objects and regular C strings. For example, suppose answer is a String object and that you have the following code:

if ("love" == answer)

This gets translated to the following:

if (operator==("love", answer))

The compiler then uses one of the constructors to convert the code, in effect, to this:

if (operator==(String("love"), answer))

And this matches the prototype.

Accessing Characters by Using Bracket Notation

With a standard C-style string, you can use brackets to access individual characters:

char city[40] = "Amsterdam";

cout << city[0] << endl; // display the letter A

In C++ the two bracket symbols constitute a single operator, the bracket operator, and you can overload this operator by using a method called operator[](). Typically, a binary C++ operator (one with two operands) puts the operator between the two operands, as in 2 + 5. But the bracket operator places one operand in front of the first bracket and the other operand between the two brackets. Thus, in the expression city[0], city is the first operand, [] is the operator, and 0 is the second operand.

Suppose that opera is a String object:

String opera("The Magic Flute");

If you use the expression opera[4], C++ looks for a method with this name and signature:

String::operator[](int i)

If it finds a matching prototype, the compiler replaces the expression opera[4] with this function call:

opera.operator[](4)

The opera object invokes the method, and the array subscript 4 becomes the function argument.

Here’s a simple implementation:

char & String::operator[](int i)

{

    return str[i];

}

With this definition, the statement

cout << opera[4];

becomes this:

cout << opera.operator[4];

The return value is opera.str[4], or the character 'M'. So the public method gives access to private data.

Declaring the return type as type char & allows you to assign values to a particular element. For example, you can use the following:

String means("might");

means[0] = 'r';

The second statement is converted to an overloaded operator function call:

means.operator[][0] = 'r';

This assigns 'r' to the method’s return value. But the function returns a reference to means.str[0], making the code equivalent to

means.str[0] = 'r';

This last line of code violates private access, but because operator[]() is a class method, it is allowed to alter the array contents. The net effect of the code is that "might" becomes "right".

Suppose you have a constant object:

const String answer("futile");

Then, if the only available definition for operator[]()is the one you’ve just seen, the following code is labeled an error:

cout << answer[1];  // compile-time error

The reason is that answer is const, and the method doesn’t promise not to alter data. (In fact, sometimes the method’s job is to alter data, so it can’t promise not to.)

However, C++ distinguishes between const and non-const function signatures when overloading, so you can provide a second version of operator[]() that is used just by const String objects:

// for use with const String objects

const char & String::operator[](int i) const

{

    return str[i];

}

With the definitions, you have read/write access to regular String objects and read-only access to const String data:

String text("Once upon a time");

const String answer("futile");

cout << text[1];    // ok, uses non-const version of operator[]()

cout << answer[1];  // ok, uses const version of operator[]()

cin >> text[1];     // ok, uses non-const version of operator[]()

cin >> answer[1];   // compile-time error

Static Class Member Functions

It’s possible to declare a member function as being static. (The keyword static should appear in the function declaration but not in the function definition if the latter is separate.) This has two important consequences.

First, a static member function doesn’t have to be invoked by an object; in fact, it doesn’t even get a this pointer to play with. If the static member function is declared in the public section, it can be invoked using the class name and the scope-resolution operator. For instance, you can give the String class a static member function called HowMany() with the following prototype/definition in the class declaration:

static int HowMany() { return num_strings; }

It could be invoked like this:

int count = String::HowMany();  // invoking a static member function

The second consequence is that because a static member function is not associated with a particular object, the only data members it can use are the static data members. For example, the HowMany() static method can access the num_strings static member, but not str or len.

Similarly, a static member function can be used to set a classwide flag that controls how some aspect of the class interface behaves. For example, it can control the formatting used by a method that displays class contents.

Further Assignment Operator Overloading

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

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

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

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