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

1. A class is a definition of a user-defined type. A class declaration specifies how data is to be stored, and it specifies the methods (class member functions) that can be used to access and manipulate that data.

2. A class represents the operations you can perform on a class object with a public interface of class methods; this is abstraction. The class can use private visibility (the default) for data members, meaning that the data can be accessed only through the member functions; this is data hiding. Details of the implementation, such as data representation and method code, are hidden; this is encapsulation.

3. A class defines a type, including how it can be used. An object is a variable or another data object, such as that produced by new, which is created and used according to the class definition. The relationship between a class and an object is the same as that between a standard type and a variable of that type.

4. If you create several objects of a given class, each object comes with storage for its own set of data. But all the objects use the one set of member functions. (Typically, methods are public and data members are private, but that’s a matter of policy, not of class requirements.)

5. This example use char arrays to hold the character data, but you could use string class objects instead.

// #include

// class definition

class BankAccount

{

private:

    char name[40];     // or std::string name;

    char acctnum[25];  // or std::string acctnum;

    double balance;

public:

    BankAccount(const char * client, const char * num, double bal = 0.0);

//or BankAccount(const std::string & client,

//               const std::string & num, double bal = 0.0);

    void show(void) const;

    void deposit(double cash);

    void withdraw(double cash);

};

6. A class constructor is called when you create an object of that class or when you explicitly call the constructor. A class destructor is called when the object expires.

7. These are two possible solutions (note that you must include cstring or string.h in order to use strncpy() or else you must include string to use the string class):

BankAccount::BankAccount(const char * client, const char * num, double bal)

{

    strncpy(name, client, 39);

    name[39] = '\0';

    strncpy(acctnum, num, 24);

    acctnum[24] = '\0';

    balance = bal;

}

or

BankAccount::BankAccount(const std::string & client,

                         const std::string & num, double bal)

{

    name = client;

    acctnum = num;

    balance = bal;

}

Keep in mind that default arguments go in the prototype, not in the function definition.

8. A default constructor either has no arguments or has defaults for all the arguments. Having a default constructor enables you to declare objects without initializing them, even if you’ve already defined an initializing constructor. It also allows you to declare arrays.

9.

// stock30.h

#ifndef STOCK30_H_

#define STOCK30_H_

class Stock

{

private:

    std::string company;

    long 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, double pr);

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

    int numshares() const { return shares; }

    double shareval() const { return share_val; }

    double totalval() const { return total_val; }

    const string & co_name() const { return company; }

};

10. The this pointer is available to class methods. It points to the object used to invoke the method. Thus, this is the address of the object, and *this represents the object itself.

Answers to Chapter Review for Chapter 11

1. Here’s a prototype for the class definition file and a function definition for the methods file:

// prototype

Stonewt operator*(double mult);

// definition — let constructor do the work

Stonewt Stonewt::operator*(double mult)

{

    return Stonewt(mult * pounds);

}

2. A member function is part of a class definition and is invoked by a particular object. The member function can access members of the invoking object implicitly, without using the membership operator. A friend function is not part of a class, so it’s called as a straight function call. It can’t access class members implicitly, so it must use the membership operator applied to an object passed as an argument. Compare, for instance, the answer to Review Question 1 with the answer to Review Question 4.

3. It must be a friend to access private members, but it doesn’t have to be a friend to access public members.

4. Here’s a prototype for the class definition file and a function definition for the methods file:

// prototype

friend Stonewt operator*(double mult, const Stonewt & s);

// definition — let constructor do the work

Stonewt operator*(double mult, const Stonewt & s)

{

    return Stonewt(mult * s.pounds);

}

5. The following five operators cannot be overloaded:

sizeof

.

.*

::

? :

6. These operators must be defined by using a member function.

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

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

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

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