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

Chapter 9

mCells = new SpreadsheetCell* [mWidth]; for (int i = 0; i < mWidth; i++) {

mCells[i] = new SpreadsheetCell[mHeight];

}

}

kMaxHeight and kMaxWidth are public, so you can access them from anywhere in your program as if they were global variables, but with slightly different syntax: you must specify that the variable is part of the Spreadsheet class with the scope resolution operator, ::.

cout << “Maximum height is: “ << Spreadsheet::kMaxHeight << endl;

Reference Data Members

Spreadsheets and SpreadsheetCells are great, but they don’t make a very useful application by themselves. You need code to control the whole spreadsheet program, which you could package into a

SpreadsheetApplication class.

The implementation of this class is unimportant at the moment. For now, consider this architecture problem: how can spreadsheets communicate with the application? The application stores a list of spreadsheets, so it can communicate with the spreadsheets. Similarly, each spreadsheet should store a reference to the application object. The Spreadsheet class must know about the SpreadsheetApplication class, but instead of using a full #include, you can just use a forward reference to the class name (see Chapter 12 for details). Here is the new Spreadsheet class definition:

class SpreadsheetApplication; // forward declaration

class Spreadsheet

{

public:

Spreadsheet(int inWidth, int inHeight,

SpreadsheetApplication& theApp); // Code omitted for brevity.

protected:

// Code omitted for brevity. SpreadsheetApplication& mTheApp;

static int sCounter;

};

Note that the application reference is given to each Spreadsheet in its constructor. A reference cannot exist without referring to something, so mTheApp must be given a value in the initializer list of the constructor:

Spreadsheet::Spreadsheet(int inWidth, int inHeight,

SpreadsheetApplication& theApp)

: mWidth(inWidth < kMaxWidth ? inWidth : kMaxWidth),

mHeight(inHeight < kMaxHeight ? inHeight : kMaxHeight), mTheApp(theApp)

{

// Code omitted for brevity.

}

198