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

private:

    enum {Lbs_per_stn = 14};      // pounds per stone

    int stone;                    // whole stones

    double pds_left;              // fractional pounds

    double pounds;                // entire weight in pounds

public:

    Stonewt(double lbs);          // construct from double pounds

    Stonewt(int stn, double lbs); // construct from stone, lbs

    Stonewt();                    // default constructor

    ~Stonewt();

    void show_lbs() const;        // show weight in pounds format

    void show_stn() const;        // show weight in stone format

// conversion functions

    operator int() const;

    operator double() const;

};

#endif

Listing 11.20 shows Listing 11.18 modified to include the definitions for these two conversion functions. Note that each function returns the desired value, even though there is no declared return type. Also note that the int conversion definition rounds to the nearest integer rather than truncating. For example, if pounds is 114.4, then pounds + 0.5 is 114.9, and int (114.9) is 114. But if pounds is 114.6, pounds + 0.5 is 115.1, and int (115.1) is 115.

Listing 11.20. stonewt1.cpp

// stonewt1.cpp -- Stonewt class methods + conversion functions

#include

using std::cout;

#include "stonewt1.h"

// construct Stonewt object from double value

Stonewt::Stonewt(double lbs)

{

    stone = int (lbs) / Lbs_per_stn;    // integer division

    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);

    pounds = lbs;

}

// construct Stonewt object from stone, double values

Stonewt::Stonewt(int stn, double lbs)

{

    stone = stn;

    pds_left = lbs;

    pounds =  stn * Lbs_per_stn +lbs;

}

Stonewt::Stonewt()          // default constructor, wt = 0

{

    stone = pounds = pds_left = 0;

}

Stonewt::~Stonewt()         // destructor

{

}

// show weight in stones

void Stonewt::show_stn() const

{

    cout << stone << " stone, " << pds_left << " pounds\n";

}

// show weight in pounds

void Stonewt::show_lbs() const

{

    cout << pounds << " pounds\n";

}

// conversion functions

Stonewt::operator int() const

{

    return int (pounds + 0.5);

}

Stonewt::operator double()const

{

    return pounds;

}

Listing 11.21 tests the new conversion functions. The assignment statement in the program uses an implicit conversion, whereas the final cout statement uses an explicit type cast. Be sure to compile Listing 11.20 along with Listing 11.21.

Listing 11.21. stone1.cpp

// stone1.cpp -- user-defined conversion functions

// compile with stonewt1.cpp

#include

#include "stonewt1.h"

int main()

{

    using std::cout;

    Stonewt poppins(9,2.8);     // 9 stone, 2.8 pounds

    double p_wt = poppins;      // implicit conversion

    cout << "Convert to double => ";

    cout << "Poppins: " << p_wt << " pounds.\n";

    cout << "Convert to int => ";

    cout << "Poppins: " << int (poppins) << " pounds.\n";

    return 0;

}

Here’s the output from the program in Listings 11.19, 11.20, and 11.21, which shows the result of converting the type Stonewt object to type double and to type int:

Convert to double => Poppins: 128.8 pounds.

Convert to int => Poppins: 129 pounds.

Applying Type Conversions Automatically

Listing 11.21 uses int (poppins) with cout. Suppose that, instead, it omitted the explicit type cast:

cout << "Poppins: " << poppins << " pounds.\n";

Would the program use an implicit conversion, as in the following statement?

double p_wt = poppins;

The answer is no. In the p_wt example, the context indicates that poppins should be converted to type double. But in the cout example, nothing indicates whether the conversion should be to int or to double. Facing this lack of information, the compiler would complain that you were using an ambiguous conversion. Nothing in the statement indicates what type to use.

Interestingly, if the class defined only the double conversion function, the compiler would accept the statement. That’s because with only one conversion possible, there is no ambiguity.

You can have a similar situation with assignment. With the current class declarations, the compiler rejects the following statement as being ambiguous:

long gone = poppins;   // ambiguous

In C++, you can assign both int and double values to a long variable, so the compiler legitimately can use either conversion function. The compiler doesn’t want the responsibility of choosing which. But if you eliminate one of the two conversion functions, the compiler accepts the statement. For example, suppose you omit the double definition. Then the compiler will use the int conversion to convert poppins to a type int value. Then it converts the int value to type long when assigning it to gone.

When the class defines two or more conversions, you can still use an explicit type cast to indicate which conversion function to use. You can use either of these type cast notations:

long gone = (double) poppins;  // use double conversion

long gone = int (poppins);     // use int conversion

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

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

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

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