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

Note that unlike in the case of ordinary function pointer assignment, here you can and must use the address operator. Having made this assignment, you can then use an object to invoke the member function:

Example ob3(20);

(ob3.*pf)();     // invoke show_inches() using the ob3 object

You need to enclose the entire ob3.*pf construction in parentheses in order to clearly identify the expression as representing a function name.

Because show_feet() has the same prototype form as show_inches(), you can use pf to access the show_feet() method, too:

pf = &Example::show_feet;

(ob3.*pf)();     // apply show_feet() to the ob3 object

The class definition presented in Listing E.1 has a use_ptr() method that uses member pointers to access both data members and function members of the Example class.

Listing E.1. memb_pt.cpp

// memb_pt.cpp -- dereferencing pointers to class members

#include

using namespace std;

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;

};

Example::Example()

{

    feet = 0;

    inches = 0;

}

Example::Example(int ft)

{

    feet = ft;

    inches = 12 * feet;

}

Example::~Example()

{

}

void Example::show_in() const

{

    cout << inches << " inches\n";

}

void Example::show_ft() const

{

    cout << feet << " feet\n";

}

void Example::use_ptr() const

{

    Example yard(3);

    int Example::*pt;

    pt = &Example::inches;

    cout << "Set pt to &Example::inches:\n";

    cout << "this->pt: " << this->*pt << endl;

    cout << "yard.*pt: " << yard.*pt << endl;

    pt = &Example::feet;

    cout << "Set pt to &Example::feet:\n";

    cout << "this->pt: " << this->*pt << endl;

    cout << "yard.*pt: " << yard.*pt << endl;

    void (Example::*pf)() const;

    pf = &Example::show_in;

    cout << "Set pf to &Example::show_in:\n";

    cout << "Using (this->*pf)(): ";

    (this->*pf)();

    cout << "Using (yard.*pf)(): ";

    (yard.*pf)();

}

int main()

{

    Example car(15);

    Example van(20);

    Example garage;

    cout << "car.use_ptr() output:\n";

    car.use_ptr();

    cout << "\nvan.use_ptr() output:\n";

    van.use_ptr();

    return 0;

}

Here is a sample run of the program in Listing E.1:

car.use_ptr() output:

Set pt to &Example::inches:

this->pt: 180

yard.*pt: 36

Set pt to &Example::feet:

this->pt: 15

yard.*pt: 3

Set pf to &Example::show_in:

Using (this->*pf)(): 180 inches

Using (yard.*pf)(): 36 inches

van.use_ptr() output:

Set pt to &Example::inches:

this->pt: 240

yard.*pt: 36

Set pt to &Example::feet:

this->pt: 20

yard.*pt: 3

Set pf to &Example::show_in:

Using (this->*pf)(): 240 inches

Using (yard.*pf)(): 36 inches

This example assigned pointer values at compile time. In a more sophisticated class, you can use member pointers to data members and methods for which the exact member associated with the pointer is determined at runtime.

alignof (C++11)

Computer systems can have restrictions on how data is stored in memory. For example, one system might require that a double value be stored at an even-numbered memory location, whereas another might require the storage to begin at a location that is a multiple of eight. The alignof operator takes a type as an argument and returns an integer indicating the required alignment type. Alignment requirements can, for example, determine how information is arranged within a structure, as Listing E.2 shows.

Listing E.2. align.cpp

// align.cpp -- checking alignment

#include

using namespace std;

struct things1

{

    char ch;

    int a;

    double x;

};

struct things2

{

    int a;

    double x;

    char ch;

};

int main()

{

    things1 th1;

    things2 th2;

    cout << "char alignment: " << alignof(char) << endl;

    cout << "int alignment: " << alignof(int) << endl;

    cout << "double alignment: " << alignof(double) << endl;

    cout << "things1 alignment: " << alignof(things1) << endl;

    cout << "things2 alignment: " << alignof(things2) << endl;

    cout << "things1 size: " << sizeof(things1) << endl;

    cout << "things2 size: " << sizeof(things2) << endl;

    return 0;

}

Here is the output on one system:

char alignment: 1

int alignment: 4

double alignment: 8

things1 alignment: 8

things2 alignment: 8

things1 size: 16

things2 size: 24

Both structures have an alignment requirement of eight. One implication is that the structure size should be a multiple of eight so that one can create arrays of structures with each element adjacent to the next and also starting on an alignment boundary that’s a multiple of eight. The individual members of each structure in Listing E.2 use only a total of 13 bits, but the requirement of using a multiple of eight bits means each structure needs some padding in it. Next, within each structure, the double member needs to align on a multiple of eight. The different arrangement of members within things1 and things2 results in things2 needing more internal padding to make the boundaries come out right.

noexcept (C++11)

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

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

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

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