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

    void onoff() {state = (state == On)? Off : On;}

    bool ison() const {return state == On;}

    bool volup();

    bool voldown();

    void chanup();

    void chandown();

    void set_mode() {mode = (mode == Antenna)? Cable : Antenna;}

    void set_input() {input = (input == TV)? DVD : TV;}

    void settings() const; // display all settings

private:

    int state;             // on or off

    int volume;            // assumed to be digitized

    int maxchannel;        // maximum number of channels

    int channel;           // current channel setting

    int mode;              // broadcast or cable

    int input;             // TV or DVD

};

class Remote

{

private:

    int mode;              // controls TV or DVD

public:

    Remote(int m = Tv::TV) : mode(m) {}

    bool volup(Tv & t) { return t.volup();}

    bool voldown(Tv & t) { return t.voldown();}

    void onoff(Tv & t) { t.onoff(); }

    void chanup(Tv & t) {t.chanup();}

    void chandown(Tv & t) {t.chandown();}

    void set_chan(Tv & t, int c) {t.channel = c;}

    void set_mode(Tv & t) {t.set_mode();}

    void set_input(Tv & t) {t.set_input();}

};

 #endif

Most of the class methods in Listing 15.1 are defined inline. Note that each Remote method other than the constructor takes a reference to a Tv object as an argument. This reflects that a remote has to be aimed at a particular TV. Listing 15.2 shows the remaining definitions. The volume-setting functions change the volume member by one unit unless the sound has reached its minimum or maximum setting. The channel selection functions use wraparound, with the lowest channel setting, taken to be 1, immediately following the highest channel setting, maxchannel.

Many of the methods use the conditional operator to toggle a state between two settings:

void onoff() {state = (state == On)? Off : On;}

Provided that the two state values are true and false, or, equivalently, 0 and 1, this can be done more compactly by using the combined bitwise exclusive OR and assignment operator (^=), as discussed in Appendix E, “Other Operators”:

void onoff() {state ^= 1;}

In fact, you could store up to eight bivalent state settings in a single unsigned char variable and toggle them individually, but that’s another story, one made possible by the bitwise operators discussed in Appendix E.

Listing 15.2. tv.cpp

// tv.cpp -- methods for the Tv class (Remote methods are inline)

#include

#include "tv.h"

bool Tv::volup()

{

    if (volume < MaxVal)

    {

        volume++;

        return true;

    }

    else

        return false;

}

bool Tv::voldown()

{

    if (volume > MinVal)

    {

        volume--;

        return true;

    }

    else

        return false;

}

void Tv::chanup()

{

    if (channel < maxchannel)

        channel++;

    else

        channel = 1;

}

void Tv::chandown()

{

    if (channel > 1)

        channel--;

    else

        channel = maxchannel;

}

void Tv::settings() const

{

    using std::cout;

    using std::endl;

    cout << "TV is " << (state == Off? "Off" : "On") << endl;

    if (state == On)

    {

        cout << "Volume setting = " << volume << endl;

        cout << "Channel setting = " << channel << endl;

        cout << "Mode = "

            << (mode == Antenna? "antenna" : "cable") << endl;

        cout << "Input = "

            << (input == TV? "TV" : "DVD") << endl;

    }

}

Listing 15.3 is a short program that tests some of the features of the program so far. The same controller is used to control two separate televisions.

Listing 15.3. use_tv.cpp

//use_tv.cpp -- using the Tv and Remote classes

#include

#include "tv.h"

int main()

{

    using std::cout;

    Tv s42;

    cout << "Initial settings for 42\" TV:\n";

    s42.settings();

    s42.onoff();

    s42.chanup();

    cout << "\nAdjusted settings for 42\" TV:\n";

    s42.settings();

    Remote grey;

    grey.set_chan(s42, 10);

    grey.volup(s42);

    grey.volup(s42);

    cout << "\n42\" settings after using remote:\n";

    s42.settings();

    Tv s58(Tv::On);

    s58.set_mode();

    grey.set_chan(s58,28);

    cout << "\n58\" settings:\n";

    s58.settings();

    return 0;

}

Here is the output of the program in Listings 15.1, 15.2, and 15.3:

Initial settings for 42" TV:

TV is Off

Adjusted settings for 42" TV:

TV is On

Volume setting = 5

Channel setting = 3

Mode = cable

Input = TV

42" settings after using remote:

TV is On

Volume setting = 7

Channel setting = 10

Mode = cable

Input = TV

58" settings:

TV is On

Volume setting = 5

Channel setting = 28

Mode = antenna

Input = TV

The main point to this exercise is that class friendship is a natural idiom in which to express some relationships. Without some form of friendship, you would either have to make the private parts of the Tv class public or else construct some awkward, larger class that encompasses both a television and a remote control. And that solution wouldn’t reflect the fact that a single remote control can be used with several televisions.

Friend Member Functions

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

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

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

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