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

    cout << pa->name << endl;

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

        cout  << pa->credit_ratings[i] <<  endl;

}

13.

typedef void (*p_f1)(applicant *);

p_f1 p1 = f1;

typedef const char * (*p_f2)(const applicant *, const applicant *);

p_f2 p2 = f2;

p_f1 ap[5];

p_f2 (*pa)[10];

Answers to Chapter Review for Chapter 8

1. Short, nonrecursive functions that can fit in one line of code are good candidates for inline status.

2.

a. void song(const char * name, int times = 1);

b. None. Only prototypes contain the default value information.

c. Yes, provided that you retain the default value for times:

void song(char * name = "O, My Papa", int times = 1);

3. You can use either the string ″\″″ or the character ′″′ to print a quotation mark. The following functions show both methods:

#include

void iquote(int n)

{

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

}

void iquote(double x)

{

    cout << '"' << x << '"';

}

void iquote(const char * str)

{

    cout << "\"" << str << "\"";

}

4.

a. This function shouldn’t alter the structure members, so use the const qualifier:

void show_box(const box & container)

{

    cout << "Made by " << container. maker << endl;

    cout << "Height = " << container.height << endl;

    cout << "Width = " << container.width << endl;

    cout << "Length = " << container.length << endl;

    cout << "Volume = " << container.volume << endl;

}

b.

void set_volume(box & crate)

{

    crate.volume = crate.height * crate.width * crate.length;

}

5. First, change the prototypes to the following:

// function to modify array object

void fill(std::array & pa);

// function that uses array object without modifying it

void show(const std::array & da);

Note that show() should use const to protect the object from being modified. Next, within main(), change the fill() call to this:

fill(expenses);

There’s no change to the show() call.

Next, the new fill() should look like this:

void fill(std::array & pa)  // changed

{

    using namespace std;

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

    {

        cout << "Enter " << Snames[i] << " expenses: ";

        cin >> pa[i];     // changed

    }

}

Note that (*pa)[i] gets changed to the simpler pa[i].

Finally, the only change to show() is to the function header:

void show(std::array & da)

6.

a. This can be done by using a default value for the second argument:

double mass(double d, double v = 1.0);

It can also be done by using function overloading:

double mass(double d, double v);

double mass(double d);

b. You can’t use a default for the repeat value because you have to provide default values from right to left. You can use overloading:

void repeat(int times, const char * str);

void repeat(const char * str);

c. You can use function overloading:

int average(int a, int b);

double average(double x, double y);

d. You can’t do this because both versions would have the same signature.

7.

template

T max(T t1, T t2)  // or T max(const T & t1, const T & t2)

{

    return t1 > t2? t1 : t2;

}

8.

template<> box max(box b1, box b2)

{

    return b1.volume > b2.volume? b1 : b2;

}

9. v1 is type float, v2 is type float &, v3 is type float &, v4 is type int, and v5 is type double. The literal 2.0 is type double, so the product 2.0 * m is double.

Answers to Chapter Review for Chapter 9

1.

a. homer is automatically an automatic variable.

b. secret should be defined as an external variable in one file and declared using extern in the second file.

c. topsecret could be defined as a static variable with internal linkage by prefacing the external definition with the keyword static. Or it could be defined in an unnamed namespace.

d. beencalled should be defined as a local static variable by prefacing a declaration in the function with the keyword static.

2. A using declaration makes available a single name from a namespace, and it has the scope corresponding to the declarative region in which the using declaration occurs. A using directive makes available all the names in a namespace. When you use a using directive, it is as if you have declared the names in the smallest declarative region containing both the using declaration and the namespace itself.

3.

#include

int main()

{

    double x;

    std::cout << "Enter value: ";

    while (! (std::cin >> x) )

    {

        std::cout << "Bad input. Please enter a number: ";

        std::cin.clear();

       while (std::cin.get() != '\n')

           continue;

    }

    std::cout << "Value = " << x << std::endl;

    return 0;

}

4. Here is the revised code:

#include

int main()

{

    using std::cin;

    using std::cout;

    using std::endl;

    double x;

    cout << "Enter value: ";

    while (! (cin >> x) )

    {

        cout << "Bad input. Please enter a number: ";

        cin.clear();

       while (cin.get() != '\n')

           continue;

    }

    cout << "Value = " << x << endl;

    return 0;

}

5. You could have separate static function definitions in each file. Or each file could define the appropriate average() function in an unnamed namespace.

6.

10

4

0

Other: 10, 1

another(): 10, -4

7.

1

4, 1, 2

2

2

4, 1, 2

2

Answers to Chapter Review for Chapter 10

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

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

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

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