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

    explicit Student(const std::string & s)


            : std::string(s), ArrayDb() {}


    explicit Student(int n) : std::string("Nully"), ArrayDb(n) {}


    Student(const std::string & s, int n)


            : std::string(s), ArrayDb(n) {}


    Student(const std::string & s, const ArrayDb & a)


            : std::string(s), ArrayDb(a) {}


    Student(const char * str, const double * pd, int n)


            : std::string(str), ArrayDb(pd, n) {}


    ~Student() {}


    double Average() const;


    double & operator[](int i);


    double operator[](int i) const;


    const std::string & Name() const;


// friends


    // input


    friend std::istream & operator>>(std::istream & is,


                                     Student & stu);  // 1 word


    friend std::istream & getline(std::istream & is,


                                  Student & stu);     // 1 line


    // output


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


                                     const Student & stu);


};



#endif


Accessing Base-Class Methods

Private inheritance limits the use of base-class methods to within derived-class methods. Sometimes, however, you might like to make a base-class facility available publicly. For example, the Student class declaration suggests the ability to use an Average() function. As with containment, the technique for doing this is to use the valarray size() and sum() methods within a public Student::average() function (see Figure 14.2). Containment invoked the methods with an object:

double Student::Average() const


{


    if (scores.size() > 0)


        return scores.sum()/scores.size();


    else


        return 0;


}

Figure 14.2. Objects within objects: private inheritance.

Here, however, inheritance lets you use the class name and the scope-resolution operator to invoke base-class methods:

double Student::Average() const


{


    if (ArrayDb::size() > 0)


        return ArrayDb::sum()/ArrayDb::size();


    else


        return 0;


}

In short, the containment approach uses object names to invoke a method, whereas private inheritance uses the class name and the scope-resolution operator instead.

Accessing Base-Class Objects

The scope-resolution operator allows you access to a base-class method, but what if you need the base-class object itself? For example, the containment version of the Student class implements the Name() method by having the method return the name member string object. But with private inheritance, the string object has no name. How, then, can Student code access the inner string object?

The answer is to use a type cast. Because Student is derived from string, it’s possible to type cast a Student object to a string object; the result is the inherited string object. Recall that the this pointer points to the invoking object, so *this is the invoking object—in this case, a type Student object. To avoid invoking constructors to create new objects, you use the type cast to create a reference:

const string & Student::Name() const


{


    return (const string &) *this;


}

This code returns a reference to the inherited string object residing in the invoking Student object.

Accessing Base-Class Friends

The technique of explicitly qualifying a function name with its class name doesn’t work for friend functions because a friend function doesn’t belong to a class. However, you can use an explicit type cast to the base class to invoke the correct functions. This is basically the same technique used to access a base-class object in a class method, but with friends you have a name for the Student object, so the code uses the name instead of *this. For example, consider the following friend function definition:

ostream & operator<<(ostream & os, const Student & stu)


{


      os << "Scores for " << (const String &) stu << ":\n";


...



}

If plato is a Student object, then the following statement invokes that function, with stu being a reference to plato and os being a reference to cout:

cout << plato;

Consider the following line of code:

os << "Scores for " << (const String &) stu << ":\n";

The typecast explicitly converts stu to a reference to a type string object; that type, in turn, invokes the operator<<(ostream &, const String &) function.

The reference stu doesn’t get converted automatically to a string reference. The fundamental reason is that with private inheritance, a reference or pointer to a base class cannot be assigned a reference or pointer to a derived class without an explicit type cast.

However, even if the example used public inheritance, it would have to use explicit type casts. One reason is that without a type cast, code like the following matches the friend function prototype, leading to a recursive call:

os << stu;

A second reason is that because the class uses MI, the compiler can’t tell which base class to convert to if both base classes happen to provide an operator<<() function. Listing 14.5 shows all the Student class methods, other than those defined inline in the class declaration.

Listing 14.5. studenti.cpp


// studenti.cpp -- Student class using private inheritance


#include "studenti.h"


using std::ostream;


using std::endl;


using std::istream;


using std::string;



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

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

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

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