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

    cout << " Address  Value\n";

    cout <<  (*p1)(av,3) << ": " << *(*p1)(av,3) << endl;

    cout << p2(av,3) << ": " << *p2(av,3) << endl;

    // pa an array of pointers

    // auto doesn't work with list initialization

    const double *(*pa[3])(const double *, int) = {f1,f2,f3};

    // but it does work for initializing to a single value

    // pb a pointer to first element of pa

    auto pb = pa;

    // pre-C++11 can use the following code instead

    // const double *(**pb)(const double *, int) = pa;

    cout << "\nUsing an array of pointers to functions:\n";

    cout << " Address  Value\n";

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

        cout << pa[i](av,3) << ": " << *pa[i](av,3) << endl;

    cout << "\nUsing a pointer to a pointer to a function:\n";

    cout << " Address  Value\n";

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

        cout << pb[i](av,3) << ": " << *pb[i](av,3) << endl;

    // what about a pointer to an array of function pointers

    cout << "\nUsing pointers to an array of pointers:\n";

    cout << " Address  Value\n";

    // easy way to declare pc

    auto pc = &pa

    // pre-C++11 can use the following code instead

    // const double *(*(*pc)[3])(const double *, int) = &pa

    cout << (*pc)[0](av,3) << ": " << *(*pc)[0](av,3) << endl;

    // hard way to declare pd

    const double *(*(*pd)[3])(const double *, int) = &pa

    // store return value in pdb

    const double * pdb = (*pd)[1](av,3);

    cout << pdb << ": " << *pdb << endl;

    // alternative notation

    cout << (*(*pd)[2])(av,3) << ": " << *(*(*pd)[2])(av,3) << endl;

    // cin.get();

    return 0;

}

// some rather dull functions

const double * f1(const double * ar, int n)

{

    return ar;

}

const double * f2(const double ar[], int n)

{

    return ar+1;

}

const double * f3(const double ar[], int n)

{

    return ar+2;

}

And here is the output:

Using pointers to functions:

 Address  Value

002AF9E0: 1112.3

002AF9E8: 1542.6

Using an array of pointers to functions:

 Address  Value

002AF9E0: 1112.3

002AF9E8: 1542.6

002AF9F0: 2227.9

Using a pointer to a pointer to a function:

 Address  Value

002AF9E0: 1112.3

002AF9E8: 1542.6

002AF9F0: 2227.9

Using pointers to an array of pointers:

 Address  Value

002AF9E0: 1112.3

002AF9E8: 1542.6

002AF9F0: 2227.9

The addresses shown are the locations of the double values in the av array.

This example may seem esoteric, but pointers to arrays of pointers to functions are not unheard of. Indeed, the usual implementation of virtual class methods (see Chapter 13, “Class Inheritance”) uses this technique. Fortunately, the compiler handles the details.

Appreciating auto

One of the goals of C++11 is to make C++ easier to use, letting the programmer concentrate more on design and less on details. Listing 7.19 surely illustrates this point:

auto pc = &pa                               // C++11 automatic type deduction

const double *(*(*pd)[3])(const double *, int) = &pa // C++98, do it yourself

The automatic type deduction feature reflects a philosophical shift in the role of the compiler. In C++98, the compiler uses its knowledge to tell you when you are wrong. In C++11, at least with this feature, it uses its knowledge to help you get the right declaration.

There is a potential drawback. Automatic type deduction ensures that the type of the variable matches the type of the initializer, but it still is possible that you might provide the wrong type of initializer:

auto pc = *pa;   // oops! used *pa instead of &pa

This declaration would make pc match the type of *pa, and that would result in a compile-time error when Listing 7.19 later uses pc, assuming that it is of the same type as &pa.

Simplifying with typedef

C++ does provide tools other than auto for simplifying declarations. You may recall from Chapter 5, “Loops and Relational Expressions,” that the typedef keyword allows you to create a type alias:

typedef double real; // makes real another name for double

The technique is to declare the alias as if it were an identifier and to insert the keyword typedef at the beginning. So you can do this to make p_fun an alias for the function pointer type used in Listing 7.19:

typedef const double *(*p_fun)(const double *, int);  // p_fun now a type name

p_fun p1 = f1;  // p1 points to the f1() function

You then can use this type to build elaborations:

p_fun pa[3] = {f1,f2,f3}; // pa an array of 3 function pointers

p_fun (*pd)[3] = &pa     // pd points to an array of 3 function pointers

Not only does typedef save you some typing, it makes writing the code less error prone, and it makes the program easier to understand.

Summary

Functions are the C++ programming modules. To use a function, you need to provide a definition and a prototype, and you have to use a function call. The function definition is the code that implements what the function does. The function prototype describes the function interface: how many and what kinds of values to pass to the function and what sort of return type, if any, to get from it. The function call causes the program to pass the function arguments to the function and to transfer program execution to the function code.

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

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

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

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