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

A PokerPlayer class derives virtually from the Person class. It has a Draw() member that returns a random number in the range 1 through 52, representing a card value. (Optionally, you could define a Card class with suit and face value members and use a Card return value for Draw().) The PokerPlayer class uses the Person show() function. The BadDude class derives publicly from the Gunslinger and PokerPlayer classes. It has a Gdraw() member that returns a bad dude’s draw time and a Cdraw() member that returns the next card drawn. It has an appropriate Show() function. Define all these classes and methods, along with any other necessary methods (such as methods for setting object values) and test them in a simple program similar to that in Listing 14.12.

5. Here are some class declarations:

// emp.h -- header file for abstr_emp class and children

#include

#include

class abstr_emp

{

private:

    std::string fname;    // abstr_emp's first name

    std::string lname;    // abstr_emp's last name

    std::string job;

public:

    abstr_emp();

    abstr_emp(const std::string & fn, const std::string &  ln,

             const std::string &  j);

    virtual void ShowAll() const;    // labels and shows all data

    virtual void SetAll();        // prompts user for values

    friend std::ostream &

             operator<<(std::ostream & os, const abstr_emp & e);

    // just displays first and last name

    virtual ~abstr_emp() = 0;         // virtual base class

};

class employee : public abstr_emp

{

public:

    employee();

    employee(const std::string & fn, const std::string &  ln,

             const std::string &  j);

    virtual void ShowAll() const;

    virtual void SetAll();

};

class manager:  virtual public abstr_emp

{

private:

    int inchargeof;        // number of abstr_emps managed

protected:

    int InChargeOf() const { return inchargeof; } // output

    int & InChargeOf(){ return inchargeof; }      // input

public:

    manager();

    manager(const std::string & fn, const std::string & ln,

            const std::string & j, int ico = 0);

    manager(const abstr_emp & e, int ico);

    manager(const manager & m);

    virtual void ShowAll() const;

    virtual void SetAll();

};

class fink: virtual public abstr_emp

{

private:

    std::string reportsto;        // to whom fink reports

protected:

    const std::string ReportsTo() const { return reportsto; }

    std::string & ReportsTo(){ return reportsto; }

public:

    fink();

    fink(const std::string & fn, const std::string & ln,

         const std::string & j, const std::string & rpo);

    fink(const abstr_emp & e, const std::string & rpo);

    fink(const fink & e);

    virtual void ShowAll() const;

    virtual void SetAll();

};

class highfink: public manager, public fink // management fink

{

public:

    highfink();

    highfink(const std::string & fn, const std::string & ln,

             const std::string & j, const std::string & rpo,

             int ico);

    highfink(const abstr_emp & e, const std::string & rpo, int ico);

    highfink(const fink & f, int ico);

    highfink(const manager & m, const std::string & rpo);

    highfink(const highfink & h);

    virtual void ShowAll() const;

    virtual void SetAll();

};

Note that the class hierarchy uses MI with a virtual base class, so keep in mind the special rules for constructor initialization lists for that case. Also note the presence of some protected-access methods. This simplifies the code for some of the highfink methods. (Note, for example, that if highfink::ShowAll() simply calls fink::ShowAll() and manager::ShowAll(), it winds up calling abstr_emp::ShowAll() twice.) Provide the class method implementations and test the classes in a program. Here is a minimal test program:

// pe14-5.cpp

// useemp1.cpp -- using the abstr_emp classes

#include

using namespace std;

#include "emp.h"

int main(void)

{

    employee em("Trip", "Harris", "Thumper");

    cout << em << endl;

    em.ShowAll();

    manager ma("Amorphia", "Spindragon", "Nuancer", 5);

    cout << ma << endl;

    ma.ShowAll();

    fink fi("Matt", "Oggs", "Oiler", "Juno Barr");

    cout << fi << endl;

    fi.ShowAll();

    highfink hf(ma, "Curly Kew");  // recruitment?

    hf.ShowAll();

    cout << "Press a key for next phase:\n";

    cin.get();

    highfink hf2;

    hf2.SetAll();

    cout << "Using an abstr_emp * pointer:\n";

    abstr_emp  * tri[4] = {&em, &fi, &hf, &hf2};

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

        tri[i]->ShowAll();

    return 0;

}

Why is no assignment operator defined?

Why are ShowAll() and SetAll() virtual?

Why is abstr_emp a virtual base class?

Why does the highfink class have no data section?

Why is only one version of operator<<() needed?

What would happen if the end of the program were replaced with this code?

abstr_emp  tri[4] = {em, fi, hf, hf2};

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

      tri[i].ShowAll();

15. Friends, Exceptions, and More

In this chapter you’ll learn about the following:

• Friend classes

• Friend class methods

• Nested classes

• Throwing exceptions, try blocks, and catch blocks

• Exception classes

• Runtime type identification (RTTI)

• dynamic_cast and typeid

• static_cast, const_cast, and reinterpret_cast

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

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

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

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