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

The program in Listing 8.6 does exactly these things. It also adds an interesting twist by having a function return a reference to the structure. This works a bit differently from returning a structure. There are some cautions to note, which we’ll get to shortly.

Listing 8.6. strc_ref.cpp

//strc_ref.cpp -- using structure references

#include

#include

struct free_throws

{

    std::string name;

    int made;

    int attempts;

    float percent;

};

void display(const free_throws & ft);

void set_pc(free_throws & ft);

free_throws & accumulate(free_throws & target, const free_throws & source);

int main()

{

// partial initializations – remaining members set to 0

    free_throws one = {"Ifelsa Branch", 13, 14};

    free_throws two = {"Andor Knott", 10, 16};

    free_throws three = {"Minnie Max", 7, 9};

    free_throws four = {"Whily Looper", 5, 9};

    free_throws five = {"Long Long", 6, 14};

    free_throws team = {"Throwgoods", 0, 0};

// no initialization

    free_throws dup;

    set_pc(one);

    display(one);

    accumulate(team, one);

    display(team);

// use return value as argument

    display(accumulate(team, two));

    accumulate(accumulate(team, three), four);

    display(team);

// use return value in assignment

    dup = accumulate(team,five);

    std::cout << "Displaying team:\n";

    display(team);

    std::cout << "Displaying dup after assignment:\n";

    display(dup);

    set_pc(four);

// ill-advised assignment

    accumulate(dup,five) = four;

    std::cout << "Displaying dup after ill-advised assignment:\n";

    display(dup);

    return 0;

}

void display(const free_throws & ft)

{

    using std::cout;

    cout << "Name: " << ft.name << '\n';

    cout << "  Made: " << ft.made << '\t';

    cout << "Attempts: " << ft.attempts << '\t';

    cout << "Percent: " << ft.percent << '\n';

}

void set_pc(free_throws & ft)

{

    if (ft.attempts != 0)

        ft.percent = 100.0f *float(ft.made)/float(ft.attempts);

    else

        ft.percent = 0;

}

free_throws & accumulate(free_throws & target, const free_throws & source)

{

    target.attempts += source.attempts;

    target.made += source.made;

    set_pc(target);

    return target;

}

Here is the program output:

Name: Ifelsa Branch

  Made: 13      Attempts: 14    Percent: 92.8571

Name: Throwgoods

  Made: 13      Attempts: 14    Percent: 92.8571

Name: Throwgoods

  Made: 23      Attempts: 30    Percent: 76.6667

Name: Throwgoods

  Made: 35      Attempts: 48    Percent: 72.9167

Displaying team:

Name: Throwgoods

  Made: 41      Attempts: 62    Percent: 66.129

Displaying dup after assignment:

Name: Throwgoods

  Made: 41      Attempts: 62    Percent: 66.129

Displaying dup after ill-advised assignment:

Name: Whily Looper

  Made: 5       Attempts: 9     Percent: 55.5556

Program Notes

The program begins by initializing several structure objects. Recall that if there are fewer initializers than members, the remaining members (just the percent members in this case) are set to 0. The first function call is this:

set_pc(one);

Because the formal parameter ft in set_pc() is a reference, ft refers to one, and the code in set_pc() sets the one.percent member. Passing by value would not work in this case because that would result in setting the percent member of a temporary copy of one. The alternative, as you may recall from the previous chapter, is using a pointer parameter and passing an address, but the form is slightly more complicated:

set_pcp(&one);    // using pointers instead - &one instead of one

...

void set_pcp(free_throws * pt)

{

    if (pt->attempts != 0)

        pt->percent = 100.0f *float(pt->made)/float(pt->attempts);

    else

        pt->percent = 0;

}

The next function call is this:

display(one);

Because display() displays the contents of the structure without altering them, the function uses a const reference parameter. In this case, one could have passed the structure by value, but using a reference is more economical in time and memory than making a copy of the original structure.

The next function call is this:

accumulate(team, one);

The accumulate() function takes two structure arguments. It adds data from the attempts and made members of the second structure to the corresponding members of the first structure. Only the first structure is modified, so the first parameter is a reference, whereas the second parameter is a const reference:

free_throws & accumulate(free_throws & target, const free_throws & source);

What about the return value? The function call we just discussed didn’t use it; as far as that use went, the function could have been type void. But look at this function call:

display(accumulate(team, two));

What’s going on here? Let’s follow the structure object team. First, team is passed to accumulate() as its first argument. That means that the target object in accumulate() really is team. The accumulate() function modifies team, then returns it as a reference. Note that the actual return statement looks like this:

return target;

Nothing in this statement indicates that a reference is being returned. That information comes from the function header (and, also, from the prototype):

free_throws & accumulate(free_throws & target, const free_throws & source)

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

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

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

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