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

7. Here are a possible prototype and definition:

// prototype and inline definition

operator double () {return mag;}

Note, however, that it makes better sense to use the magval() method than to define this conversion function.

Answers to Chapter Review for Chapter 12

1.

a. The syntax is fine, but this constructor leaves the str pointer uninitialized. The constructor should either set the pointer to NULL or use new [] to initialize the pointer.

b. This constructor does not create a new string; it merely copies the address of the old string. It should use new [] and strcpy().

c. It copies the string without allocating the space to store it. It should use new char[len + 1] to allocate the proper amount of memory.

2. First, when an object of that type expires, the data pointed to by the object’s member pointer remains in memory, using space and remaining inaccessible because the pointer has been lost. That can be fixed by having the class destructor delete memory allocated by new in the constructor functions. Second, after the destructor deletes such memory, it might end up trying to delete it twice if a program initializes one such object to another. That’s because the default initialization of one object to another copies pointer values but does not copy the pointed-to data, and this produces two pointers to the same data. The solution is to define a class copy constructor that causes initialization to copy the pointed-to data. Third, assigning one object to another can produce the same situation of two pointers pointing to the same data. The solution is to overload the assignment operator so that it copies the data, not the pointers.

3. C++ automatically provides the following member functions:

• A default constructor if you define no constructors

• A copy constructor if you don’t define one

• An assignment operator if you don’t define one

• A default destructor if you don’t define one

• An address operator if you don’t define one

The default constructor does nothing, but it allows you to declare arrays and uninitialized objects. The default copy constructor and the default assignment operator use memberwise assignment. The default destructor does nothing. The implicit address operator returns the address of the invoking object (that is, the value of the this pointer).

4. The personality member should be declared either as a character array or as a pointer-to-char. Or you could make it a String object or a string object. The declaration fails to make the methods public. Then there are several small errors. Here is a possible solution, with changes (other than deletions) in boldface:

#include

#include

using namespace std;

class nifty

{

private: // optional

    char personality[40];    // provide array size

    int talents;

public: // needed

// methods

    nifty();

    nifty(const char * s);

    friend ostream & operator<<(ostream & os, const nifty & n);

};    // note closing semicolon

nifty::nifty()

{

    personality[0] = '\0';

    talents = 0;

}

nifty::nifty(const char * s)

{

    strcpy(personality, s);

    talents = 0;

}

ostream & operator<<(ostream & os, const nifty & n)

{

    os << n.personality << '\n';

    os << n.talent << '\n';

    return os;

}

Here is another possible solution:

#include

#include

using namespace std;

class nifty

{

private: // optional

    char * personality;    // create a pointer

    int talents;

public: // needed

// methods

    nifty();

    nifty(const char * s);

    nifty(const nifty & n);

    ~nifty() { delete [] personality; }

    nifty & operator=(const nifty & n) const;

    friend ostream & operator<<(ostream & os, const nifty & n);

};    // note closing semicolon

nifty::nifty()

{

    personality = NULL;

    talents = 0;

}

nifty::nifty(const char * s)

{

    personality = new char [strlen(s) + 1];

    strcpy(personality, s);

    talents = 0;

}

ostream & operator<<(ostream & os, const nifty & n)

{

    os << n.personality << '\n';

    os << n.talent << '\n';

    return os;

}

5.

a.

Golfer nancy; // default constructor

Golfer lulu("Little Lulu"); // Golfer(const char * name, int g)

Golfer roy("Roy Hobbs", 12); // Golfer(const char * name, int g)

Golfer * par = new Golfer; // default constructor

Golfer next = lulu; // Golfer(const Golfer &g)

Golfer hazard = "Weed Thwacker"; // Golfer(const char * name, int g)

*par = nancy; // default assignment operator

nancy = "Nancy Putter";// Golfer(const char * name, int g), then

                  // the default assignment operator

Note that some compilers additionally call the default assignment operator for Statements 5 and 6.

b. The class should define an assignment operator that copies data rather than addresses.

Answers to Chapter Review for Chapter 13

1. The public members of the base class become public members of the derived class. The protected members of the base class become protected members of the derived class. The private members of the base class are inherited but cannot be accessed directly. The answer to Review Question 2 provides the exceptions to these general rules.

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

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

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

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