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

    void Vector::set_y()

    {

        y = mag * sin(ang);

    }

    // public methods

    Vector::Vector()             // default constructor

    {

        x = y = mag = ang = 0.0;

        mode = RECT;

    }

    // construct vector from rectangular coordinates if form is r

    // (the default) or else from polar coordinates if form is p

    Vector::Vector(double n1, double n2, Mode form)

    {

        mode = form;

        if (form == RECT)

         {

             x = n1;

             y = n2;

             set_mag();

             set_ang();

        }

        else if (form == POL)

        {

             mag = n1;

             ang = n2 / Rad_to_deg;

             set_x();

             set_y();

        }

        else

        {

             cout << "Incorrect 3rd argument to Vector() -- ";

             cout << "vector set to 0\n";

             x = y = mag = ang = 0.0;

             mode = RECT;

        }

    }

    // reset vector from rectangular coordinates if form is

    // RECT (the default) or else from polar coordinates if

    // form is POL

    void Vector:: reset(double n1, double n2, Mode form)

    {

        mode = form;

        if (form == RECT)

         {

             x = n1;

             y = n2;

             set_mag();

             set_ang();

        }

        else if (form == POL)

        {

             mag = n1;

             ang = n2 / Rad_to_deg;

             set_x();

             set_y();

        }

        else

        {

             cout << "Incorrect 3rd argument to Vector() -- ";

             cout << "vector set to 0\n";

             x = y = mag = ang = 0.0;

             mode = RECT;

        }

    }

    Vector::~Vector()    // destructor

    {

    }

    void Vector::polar_mode()    // set to polar mode

    {

        mode = POL;

    }

    void Vector::rect_mode()     // set to rectangular mode

    {

        mode = RECT;

    }

    // operator overloading

    // add two Vectors

    Vector Vector::operator+(const Vector & b) const

    {

        return Vector(x + b.x, y + b.y);

    }

    // subtract Vector b from a

    Vector Vector::operator-(const Vector & b) const

    {

        return Vector(x - b.x, y - b.y);

    }

    // reverse sign of Vector

    Vector Vector::operator-() const

    {

        return Vector(-x, -y);

    }

    // multiply vector by n

    Vector Vector::operator*(double n) const

    {

        return Vector(n * x, n * y);

    }

    // friend methods

    // multiply n by Vector a

    Vector operator*(double n, const Vector & a)

    {

        return a * n;

    }

    // display rectangular coordinates if mode is RECT,

    // else display polar coordinates if mode is POL

    std::ostream & operator<<(std::ostream & os, const Vector & v)

    {

        if (v.mode == Vector::RECT)

             os << "(x,y) = (" << v.x << ", " << v.y << ")";

        else if (v.mode == Vector::POL)

        {

             os << "(m,a) = (" << v.mag << ", "

                 << v.ang * Rad_to_deg << ")";

        }

        else

             os << "Vector object mode is invalid";

        return os;

    }

}  // end namespace VECTOR

You could design the class differently. For example, the object could store the rectangular coordinates and not the polar coordinates. In that case, the computation of polar coordinates could be moved to the magval() and angval() methods. For applications in which conversions are seldom used, this could be a more efficient design. Also the reset() method isn’t really needed. Suppose shove is a Vector object and that you have the following code:

shove.reset(100,300);

You can get the same result by using a constructor instead:

shove = Vector(100,300);    // create and assign a temporary object

However, the set() method alters the contents of shove directly, whereas using the constructor adds the extra steps of creating a temporary object and assigning it to shove.

These design decisions follow the OOP tradition of having the class interface concentrate on the essentials (the abstract model) while hiding the details. Thus, when you use the Vector class, you can think about a vector’s general features, such as that they can represent displacements and that you can add two vectors. Whether you express a vector in component notation or in magnitude, direction notation becomes secondary because you can set a vector’s values and display them in whichever format is most convenient at the time.

We’ll look at some of the features the Vector class in more detail next.

Using a State Member

The Vector class stores both the rectangular coordinates and the polar coordinates for a vector. It uses a member called mode to control which form the constructor, the reset() method, and the overloaded operator<<() function use, with the enumerations RECT representing the rectangular mode (the default) and POL the polar mode. Such a member is termed a state member because it describes the state an object is in. To see what this means, look at the code for the constructor:

Vector::Vector(double n1, double n2, Mode form)

{

    mode = form;

    if (form == RECT)

    {

         x = n1;

         y = n2;

         set_mag();

         set_ang();

    }

    else if (form == POL)

    {

         mag = n1;

         ang = n2 / Rad_to_deg;

         set_x();

         set_y();

    }

    else

    {

         cout << "Incorrect 3rd argument to Vector() -- ";

         cout << "vector set to 0\n";

         x = y = mag = ang = 0.0;

         mode = RECT;

    }

}

If the third argument is RECT or if it is omitted (in which case the prototype assigns a default value of RECT), the inputs are interpreted as rectangular coordinates, whereas a value of POL causes them to be interpreted as polar coordinates:

Vector folly(3.0, 4.0);            // set x = 3, y = 4

Vector foolery(20.0, 30.0, VECTOR::Vector::POL);   // set mag = 20, ang = 30

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

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

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

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