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

Here s.total_val is the total value for the object passed as an argument, and total_val is the total value for the object to which the message is sent. If s.total_val is greater than total_val, the function returns a reference to s. Otherwise, it returns a reference to the object used to evoke the method. (In OOP talk, that is the object to which the topval message is sent.) Here’s the problem: What do you call that object? If you make the call stock1.topval(stock2), then s is a reference for stock2 (that is, an alias for stock2), but there is no alias for stock1.

The C++ solution to this problem is to use a special pointer called this. The this pointer points to the object used to invoke a member function. (Basically, this is passed as a hidden argument to the method.) Thus, the function call stock1.topval(stock2) sets this to the address of the stock1 object and makes that pointer available to the topval() method. Similarly, the function call stock2.topval(stock1) sets this to the address of the stock2 object. In general, all class methods have a this pointer set to the address of the object that invokes the method. Indeed, total_val in topval() is just shorthand notation for this->total_val. (Recall from Chapter 4, “Compound Types,” that you use the -> operator to access structure members via a pointer. The same is true for class members.) (See Figure 10.4.)

Figure 10.4. this points to the invoking object.

Note

Each member function, including constructors and destructors, has a this pointer. The special property of the this pointer is that it points to the invoking object. If a method needs to refer to the invoking object as a whole, it can use the expression *this. Using the const qualifier after the function argument parentheses qualifies this as being a pointer to const; in that case, you can’t use this to change the object’s value.

What you want to return, however, is not this because this is the address of the object. You want to return the object itself, and that is symbolized by *this. (Recall that applying the dereferencing operator * to a pointer yields the value to which the pointer points.) Now you can complete the method definition by using *this as an alias for the invoking object:

const Stock & Stock::topval(const Stock & s) const

{

    if (s.total_val > total_val)

       return s;           // argument object

    else

       return *this;       // invoking object

}

The fact that the return type is a reference means that the returned object is the invoking object itself rather than a copy passed by the return mechanism. Listing 10.7 shows the new header file.

Listing 10.7. stock20.h

// stock20.h -- augmented version

#ifndef STOCK20_H_

#define STOCK20_H_

#include

class Stock

{

private:

    std::string company;

    int shares;

    double share_val;

    double total_val;

    void set_tot() { total_val = shares * share_val; }

public:

    Stock();        // default constructor

    Stock(const std::string & co, long n = 0, double pr = 0.0);

    ~Stock();       // do-nothing destructor

    void buy(long num, double price);

    void sell(long num, double price);

    void update(double price);

    void show()const;

    const Stock & topval(const Stock & s) const;

};

#endif

Listing 10.8 presents the revised class methods file. It includes the new topval() method. Also now that you’ve seen how the constructors and destructor work, Listing 10.8 replaces them with silent versions.

Listing 10.8. stock20.cpp

// stock20.cpp -- augmented version

#include

#include "stock20.h"

// constructors

Stock::Stock()        // default constructor

{

    company = "no name";

    shares = 0;

    share_val = 0.0;

    total_val = 0.0;

}

Stock::Stock(const std::string & co, long n, double pr)

{

    company = co;

    if (n < 0)

    {

        std::cout << "Number of shares can't be negative; "

                   << company << " shares set to 0.\n";

        shares = 0;

    }

    else

        shares = n;

    share_val = pr;

    set_tot();

}

// class destructor

Stock::~Stock()        // quiet class destructor

{

}

// other methods

void Stock::buy(long num, double price)

{

     if (num < 0)

    {

        std::cout << "Number of shares purchased can't be negative. "

             << "Transaction is aborted.\n";

    }

    else

    {

        shares += num;

        share_val = price;

        set_tot();

    }

}

void Stock::sell(long num, double price)

{

    using std::cout;

    if (num < 0)

    {

        cout << "Number of shares sold can't be negative. "

             << "Transaction is aborted.\n";

    }

    else if (num > shares)

    {

        cout << "You can't sell more than you have! "

             << "Transaction is aborted.\n";

    }

    else

    {

        shares -= num;

        share_val = price;

        set_tot();

    }

}

void Stock::update(double price)

{

    share_val = price;

    set_tot();

}

void Stock::show() const

{

    using std::cout;

    using std::ios_base;

    // set format to #.###

    ios_base::fmtflags orig =

        cout.setf(ios_base::fixed, ios_base::floatfield);

    std::streamsize prec = cout.precision(3);

    cout << "Company: " << company

        << "  Shares: " << shares << '\n';

    cout << "  Share Price: $" << share_val;

    // set format to #.##

    cout.precision(2);

    cout << "  Total Worth: $" << total_val << '\n';

    // restore original format

    cout.setf(orig, ios_base::floatfield);

    cout.precision(prec);

}

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

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

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

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