Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

168 Part III: Introduction to Classes

Activating Our Objects

You use classes to simulate real-world objects. The Savings class tries to represent a savings account. This allows you to think in terms of objects rather than simply lines of code. The closer C++ objects are to the real world, the easier it is to deal with them in programs. This sounds simple enough. However, the Savings class doesn’t do a very good job of simulating a sav­ ings account.

Simulating real-world objects

Real-world objects have data-type properties such as account numbers and balances, the same as the Savings class. This makes Savings a good start­ ing point for describing a real object. But real-world objects do things. Ovens cook. Savings accounts accumulate interest, CDs charge a substantial penalty for early withdrawal — stuff like that.

Functional programs “do things” via functions. A C++ program might call strcmp() to compare two strings or max() to return the maximum of two values. In fact, Chapter 24 explains that even stream I/O (cin >> and cout <<) is a special form of function call.

The Savings class needs active properties of its own if its to do a good job of representing a real concept:

class Savings

{

public:

float deposit(float amount)

{

balance += amount;

return balance;

}

unsigned int accountNumber; float balance;

};

In addition to the account number and balance, this version of Savings includes the function deposit(). This gives Savings the ability to control its own future. A class MicrowaveOven has the function cook(), the class Savings has the function accumulateInterest(), and the class CD has the function penalizeForEarlyWithdrawal().

Functions defined in a class are called member functions.