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

    Cd(char * s1, char * s2, int n, double x);


    Cd(const Cd & d);


    Cd();


    ~Cd();


    void Report() const;  // reports all CD data


    Cd & operator=(const Cd & d);


};

Derive a Classic class that adds an array of char members that will hold a string identifying the primary work on the CD. If the base class requires that any functions be virtual, modify the base-class declaration to make it so. If a declared method is not needed, remove it from the definition. Test your product with the following program:

#include


using namespace std;


#include "classic.h"     // which will contain #include cd.h


void Bravo(const Cd & disk);


int main()


{


    Cd c1("Beatles", "Capitol", 14, 35.5);


    Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C",


                     "Alfred Brendel", "Philips", 2, 57.17);


    Cd *pcd = &c1



    cout << "Using object directly:\n";


    c1.Report();    // use Cd method


    c2.Report();    // use Classic method



    cout << "Using type cd * pointer to objects:\n";


    pcd->Report();  // use Cd method for cd object


    pcd = &c2


    pcd->Report();  // use Classic method for classic object



    cout << "Calling a function with a Cd reference argument:\n";


    Bravo(c1);


    Bravo(c2);



    cout << "Testing assignment: ";


    Classic copy;


    copy = c2;


    copy.Report()



    return 0;


}



void Bravo(const Cd & disk)


{


    disk.Report();


}

2. Do Programming Exercise 1 but use dynamic memory allocation instead of fixed-size arrays for the various strings tracked by the two classes.

3. Revise the baseDMA-lacksDMA-hasDMA class hierarchy so that all three classes are derived from an ABC. Test the result with a program similar to the one in Listing 13.10. That is, it should feature an array of pointers to the ABC and allow the user to make runtime decisions as to what types of objects are created. Add virtual View() methods to the class definitions to handle displaying the data.

4. The Benevolent Order of Programmers maintains a collection of bottled port. To describe it, the BOP Portmaster has devised a Port class, as declared here:

#include


using namespace std;


class Port


{


private:


    char * brand;


    char style[20]; // i.e., tawny, ruby, vintage


    int bottles;


public:


    Port(const char * br = "none", const char * st = "none", int b = 0);


    Port(const Port & p);                // copy constructor


    virtual ~Port() { delete [] brand; }


    Port & operator=(const Port & p);


    Port & operator+=(int b);            // adds b to bottles


    Port & operator-=(int b);            // subtracts b from bottles, if available


    int BottleCount() const { return bottles; }


    virtual void Show() const;


    friend ostream & operator<<(ostream & os, const Port & p);


};

The Show() method presents information in the following format:

Brand: Gallo


Kind: tawny


Bottles: 20

The operator<<() function presents information in the following format (with no newline character at the end):

Gallo, tawny, 20

The Portmaster completed the method definitions for the Port class and then derived the VintagePort class as follows before being relieved of his position for accidentally routing a bottle of ‘45 Cockburn to someone preparing an experimental barbecue sauce:

class VintagePort : public Port // style necessarily = "vintage"


{


private:


    char * nickname;           // i.e., "The Noble" or "Old Velvet", etc.


    int year;                  // vintage year


public:


    VintagePort();


    VintagePort(const char * br, int b, const char * nn, int y);


    VintagePort(const VintagePort & vp);


    ~VintagePort() { delete [] nickname; }


    VintagePort & operator=(const VintagePort & vp);


    void Show() const;


    friend ostream & operator<<(ostream & os, const VintagePort & vp);


};

You get the job of completing the VintagePort work.

a. Your first task is to re-create the Port method definitions because the former Portmaster immolated his upon being relieved.

b. Your second task is to explain why certain methods are redefined and others are not.

c. Your third task is to explain why operator=() and operator<<() are not virtual.

d. Your fourth task is to provide definitions for the VintagePort methods.

14. Reusing Code in C++

In this chapter you’ll learn about the following:

Has-a relationships

• Classes with member objects (containment)

• The valarray template class

• Private and protected inheritance

• Multiple inheritance

• Virtual base classes

• Creating class templates

• Using class templates

• Template specializations

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

Все книги серии 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.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

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

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