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

    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";

}

Because a Stonewt object represents a single weight, it makes sense to provide ways to convert an integer or a floating-point value to a Stonewt object. And you have already done so! In C++, any constructor that takes a single argument acts as a blueprint for converting a value of that argument type to the class type. Thus the following constructor serves as instructions for converting a type double value to a type Stonewt value:

Stonewt(double lbs);  // template for double-to-Stonewt conversion

That is, you can write code like the following:

Stonewt myCat;        // create a Stonewt object

myCat = 19.6;         // use Stonewt(double) to convert 19.6 to Stonewt

The program uses the Stonewt(double) constructor to construct a temporary Stonewt object, using 19.6 as the initialization value. Then memberwise assignment copies the contents of the temporary object into myCat. This process is termed an implicit conversion because it happens automatically, without the need of an explicit type cast.

Only a constructor that can be used with just one argument works as a conversion function. The following constructor has two arguments, so it cannot be used to convert types:

Stonewt(int stn, double lbs);  // not a conversion function

However, it would act as a guide to int conversion if it provided a default value for the second parameter:

Stonewt(int stn, double lbs = 0);  // int-to-Stonewt conversion

Having a constructor work as an automatic type-conversion function seems like a nice feature. As programmers acquired more experience working with C++, however, they found that the automatic aspect isn’t always desirable because it can lead to unexpected conversions. So C++ added a new keyword, explicit, to turn off the automatic aspect. That is, you can declare the constructor this way:

explicit Stonewt(double lbs);   // no implicit conversions allowed

This turns off implicit conversions such as the preceding example but still allows explicit conversions—that is, conversions using explicit type casts:

Stonewt myCat;          // create a Stonewt object

myCat = 19.6;           // not valid if Stonewt(double) is declared as explicit

mycat = Stonewt(19.6);  // ok, an explicit conversion

mycat = (Stonewt) 19.6; // ok, old form for explicit typecast

Note

A C++ constructor that contains one argument defines a type conversion from the argument type to the class type. If the constructor is qualified with the keyword explicit, the constructor is used for explicit conversions only; otherwise, it is also used for implicit conversions.

When does the compiler use the Stonewt(double) function? If the keyword explicit is used in the declaration, Stonewt(double) is used only for an explicit type cast; otherwise, it is also used for the following implicit conversions:

• When you initialize a Stonewt object to a type double value

• When you assign a type double value to a Stonewt object

• When you pass a type double value to a function that expects a Stonewt argument

• When a function that’s declared to return a Stonewt value tries to return a double value

• When any of the preceding situations use a built-in type that can unambiguously be converted to type double

Let’s look at the last point in more detail. The argument-matching process provided by function prototyping lets the Stonewt(double) constructor act as conversions for other numerical types. That is, both of the following statements work by first converting int to double and then using the Stonewt(double) constructor:

Stonewt Jumbo(7000);   // uses Stonewt(double), converting int to double

Jumbo = 7300;          // uses Stonewt(double), converting int to double

However, this two-step conversion process works only if there is an unambiguous choice. That is, if the class also defined a Stonewt(long) constructor, the compiler would reject these statements, probably pointing out that an int can be converted to either a long or a double, so the call is ambiguous.

Listing 11.18 uses the class constructors to initialize some Stonewt objects and to handle type conversions. Be sure to compile Listing 11.17 along with Listing 11.18.

Listing 11.18. stone.cpp

// stone.cpp -- user-defined conversions

// compile with stonewt.cpp

#include

using std::cout;

#include "stonewt.h"

void display(const Stonewt & st, int n);

int main()

{

    Stonewt incognito = 275; // uses constructor to initialize

    Stonewt wolfe(285.7);    // same as Stonewt wolfe = 285.7;

    Stonewt taft(21, 8);

    cout << "The celebrity weighed ";

    incognito.show_stn();

    cout << "The detective weighed ";

    wolfe.show_stn();

    cout << "The President weighed ";

    taft.show_lbs();

    incognito = 276.8;      // uses constructor for 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.

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

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