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

But using function notation instead of operator notation lets you use the scope-resolution operator. In effect, the statement means the following:

*this = hs;  // use baseDMA::operator=()

But, of course, the compiler ignores comments, so if you used the latter code, the compiler would use hasDMA::operator=() instead and create a recursive call. Using function notation gets the correct assignment operator called.

In summary, when both the base class and the derived class use dynamic memory allocation, the derived-class destructor, copy constructor, and assignment operator all must use their base-class counterparts to handle the base-class component. This common requirement is accomplished three different ways. For a destructor, it is done automatically. For a constructor, it is accomplished by invoking the base-class copy constructor in the member initialization list, or else the default constructor is invoked automatically. For the assignment operator, it is accomplished by using the scope-resolution operator in an explicit call of the base-class assignment operator.

An Inheritance Example with Dynamic Memory Allocation and Friends

To illustrate these ideas of inheritance and dynamic memory allocation, let’s integrate the baseDMA, lacksDMA, and hasDMA classes just discussed into a single example. Listing 13.14 is a header file for these classes. To what we’ve already discussed, it adds a friend function that illustrates how derived classes can access friends to a base class.

Listing 13.14. dma.h


// dma.h  -- inheritance and dynamic memory allocation


#ifndef DMA_H_


#define DMA_H_


#include



//  Base Class Using DMA


class baseDMA


{


private:


    char * label;


    int rating;



public:


    baseDMA(const char * l = "null", int r = 0);


    baseDMA(const baseDMA & rs);


    virtual ~baseDMA();


    baseDMA & operator=(const baseDMA & rs);


    friend std::ostream & operator<<(std::ostream & os,


                                     const baseDMA & rs);


};



// derived class without DMA


// no destructor needed


// uses implicit copy constructor


// uses implicit assignment operator


class lacksDMA :public baseDMA


{


private:


    enum { COL_LEN = 40};


    char color[COL_LEN];


public:


    lacksDMA(const char * c = "blank", const char * l = "null",


              int r = 0);


    lacksDMA(const char * c, const baseDMA & rs);


    friend std::ostream & operator<<(std::ostream & os,


                                     const lacksDMA & rs);


};



// derived class with DMA


class hasDMA :public baseDMA


{


private:


    char * style;


public:


    hasDMA(const char * s = "none", const char * l = "null",


              int r = 0);


    hasDMA(const char * s, const baseDMA & rs);


    hasDMA(const hasDMA & hs);


    ~hasDMA();


    hasDMA & operator=(const hasDMA & rs);


    friend std::ostream & operator<<(std::ostream & os,


                                     const hasDMA & rs);


};



#endif


Listing 13.15 provides the method definitions for the baseDMA, lacksDMA, and hasDMA classes.

Listing 13.15. dma.cpp


// dma.cpp --dma class methods



#include "dma.h"


#include



// baseDMA methods


baseDMA::baseDMA(const char * l, int r)


{


    label = new char[std::strlen(l) + 1];


    std::strcpy(label, l);


    rating = r;


}



baseDMA::baseDMA(const baseDMA & rs)


{


    label = new char[std::strlen(rs.label) + 1];


    std::strcpy(label, rs.label);


    rating = rs.rating;


}



baseDMA::~baseDMA()


{


    delete [] label;


}



baseDMA & baseDMA::operator=(const baseDMA & rs)


{


    if (this == &rs)


        return *this;


    delete [] label;


    label = new char[std::strlen(rs.label) + 1];


    std::strcpy(label, rs.label);


    rating = rs.rating;


    return *this;


}



std::ostream & operator<<(std::ostream & os, const baseDMA & rs)


{


    os << "Label: " << rs.label << std::endl;


    os << "Rating: " << rs.rating << std::endl;


    return os;


}



// lacksDMA methods


lacksDMA::lacksDMA(const char * c, const char * l, int r)


    : baseDMA(l, r)


{


    std::strncpy(color, c, 39);


    color[39] = '\0';


}



lacksDMA::lacksDMA(const char * c, const baseDMA & rs)


    : baseDMA(rs)


{


    std::strncpy(color, c, COL_LEN - 1);


    color[COL_LEN - 1] = '\0';


}



std::ostream & operator<<(std::ostream & os, const lacksDMA & ls)


{


    os << (const baseDMA &) ls;


    os << "Color: " << ls.color << std::endl;


    return os;


}



// hasDMA methods


hasDMA::hasDMA(const char * s, const char * l, int r)


         : baseDMA(l, r)


{


    style = new char[std::strlen(s) + 1];


    std::strcpy(style, s);


}



hasDMA::hasDMA(const char * s, const baseDMA & rs)


         : baseDMA(rs)


{


    style = new char[std::strlen(s) + 1];


    std::strcpy(style, s);


}



hasDMA::hasDMA(const hasDMA & hs)


         : baseDMA(hs)  // invoke base class copy constructor


{


    style = new char[std::strlen(hs.style) + 1];


    std::strcpy(style, hs.style);


}



hasDMA::~hasDMA()


{


    delete [] style;


}



hasDMA & hasDMA::operator=(const hasDMA & hs)


{


    if (this == &hs)


        return *this;


    baseDMA::operator=(hs);  // copy base portion


    delete [] style;         // prepare for new style


    style = new char[std::strlen(hs.style) + 1];


    std::strcpy(style, hs.style);


    return *this;


}



std::ostream & operator<<(std::ostream & os, const hasDMA & hs)


{


    os << (const baseDMA &) hs;


    os << "Style: " << hs.style << std::endl;


    return os;


}


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

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

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

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