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

These statements turn the bit off, regardless of its prior state. First, the operator ~bit produces an integer with all its bits set to 1 except the bit that originally was set to 1; that bit becomes 0. ANDing a 0 with any bit results in 0, thus turning that bit off. All other bits in lottabits are unchanged. That’s because ANDing a 1 with any bit produces the value that bit had before.

Here’s a briefer way of doing the same thing:

lottabits &= ~bit;

Testing a Bit Value

Suppose you want to determine whether the bit corresponding to bit is set to 1 in lottabits. The following test does not necessarily work:

if (lottabits == bit)             // no good

That’s because even if the corresponding bit in lottabits is set to 1, other bits might also be set to 1. The equality above is true only when the corresponding bit is 1. The fix is to first AND lottabits with bit. This produces a value that is 0 in all the other bit positions because 0 AND any value is 0. Only the bit corresponding to the bit value is left unchanged because 1 AND any value is that value. Thus the proper test is this:

if (lottabits & bit == bit)       // testing a bit

Real-world programmers often simplify this test to the following:

if (lottabits & bit)       // testing a bit

Because bit consists of one bit set to 1 and the rest set to 0, the value of lottabits & bit is either 0 (which tests as false) or bit, which, being nonzero, tests as true.

Member Dereferencing Operators

C++ lets you define pointers to members of a class. These pointers involve special notations to declare them and to dereference them. To see what’s involved, let’s start with a sample class:

class Example

{

private:

    int feet;

    int inches;

public:

    Example();

    Example(int ft);

    ~Example();

    void show_in() const;

    void show_ft() const;

    void use_ptr() const;

};

Consider the inches member. Without a specific object, inches is a label. That is, the class defines inches as a member identifier, but you need an object before you actually have memory allocated:

Example ob;  // now ob.inches exists

Thus, you specify an actual memory location by using the identifier inches in conjunction with a specific object. (In a member function, you can omit the name of the object, but then the object is understood to be the one pointed to by the pointer.)

C++ lets you define a member pointer to the identifier inches like this:

int Example::*pt = &Example::inches;

This pointer is a bit different from a regular pointer. A regular pointer points to a specific memory location. But the pt pointer doesn’t point to a specific memory location because the declaration doesn’t identify a specific object. Instead, the pointer pt identifies the location of inches member within any Example object. Like the identifier inches, pt is designed to be used in conjunction with an object identifier. In essence, the expression *pt assumes the role of the identifier inches. Therefore, you can use an object identifier to specify which object to access and the pt pointer to specify the inches member of that object. For example, a class method could use this code:

int Example::*pt = &Example::inches;

Example ob1;

Example ob2;

Example *pq = new Example;

cout << ob1.*pt << endl; // display inches member of ob1

cout << ob2.*pt << endl; // display inches member of ob2

cout << po->*pt << endl; // display inches member of *po

Here .* and ->* are member dereferencing operators. When you have a particular object, such as ob1, then ob1.*pi identifies the inches member of the ob1 object. Similarly, pq->*pt identifies the inches member of an object pointed to by pq.

Changing the object in the preceding example changes which inches member is used. But you can also change the pt pointer itself. Because feet is of the same type as inches, you can reset pt to point to the feet member instead of the inches member; then ob1.*pt will refer to the feet member of ob1:

pt = &Example::feet;      // reset pt

cout << ob1.*pt << endl;  // display feet member of ob1

In essence, the combination *pt takes the place of a member name and can be used to identify different member names (of the same type).

You can also use member pointers to identify member functions. The syntax for this is relatively involved. Recall that declaring a pointer to an ordinary type void function with no arguments looks like this:

void (*pf)();  // pf points to a function

Declaring a pointer to a member function has to indicate that the function belongs to a particular class. Here, for instance, is how to declare a pointer to an Example class method:

void (Example::*pf)() const;  // pf points to an Example member function

This indicates that pf can be used the same places that Example method can be used. Note that the term Example: :*pf has to be in parentheses. You can assign the address of a particular member function to this pointer:

pf = &Example::show_inches;

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

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

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

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