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

296 Part IV: Inheritance

namespace Schools

{

char* GraduateStudent::display()

{

//get description of basic student char* pFirst = Student::display();

//we’ll add this text

char* pSecond = “-G”;

// get a new string and tack second onto first char* pName = new char[strlen(pFirst) +

strlen(pSecond) + 1];

strcpy(pName, pFirst); strcat(pName, pSecond);

//don’t forget to return the string returned by

//Student::display() to the heap before passing

//our new string to the caller

delete pFirst; return pName;

}

}

The GraduateStudent version of display() concatenates a “-G” onto the end of whatever Student returns. It begins by allocating a new character array that’s large enough to handle the extra information.

Never assume that there’s enough room in the original buffer for any extra characters to be tacked onto the end.

The program copies the contents of the original string into the newly allo­ cated array. It then appends the “- G”. The display() function must return the buffer allocated by Student::display() to the heap before continuing.

Forgetting to return buffers to the heap is known as a memory leak. A pro­ gram with memory leaks executes properly at first; however, the program slows more and more as the available memory is lost to the leaks. The pro­ gram eventually grinds to a halt. Memory leaks are very difficult to find.

Implementing an application

The two classes, Student and GraduateStudent, have been separated into independent source files and included in the Schools namespace. I wrote the following very simple application to invoke the two classes:

Chapter 22: Factoring Classes 297

// SeparatedMain - demonstrated an application separated // into two parts - the main() part #include <cstdio>

#include <cstdlib> #include <iostream>

#include “graduateStudent.h” #include “student.h”

using namespace std; //using namespace Schools;

using Schools::GraduateStudent;

int main(int nArgc, char* pszArgs[])

{

Schools::Student s(“Sophie Moore”, 1234); cout << “Student = “ << s.display() << endl;

GraduateStudent gs(“Greg U. Waite”, 5678); cout << “Student = “ << gs.display() << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

The application includes both the student.h and graduateStudent.h include files. This gives the application access to the definition of the two classes.

You might notice that including graduatestudent.h automatically includes student.h. However, you shouldn’t take it for granted; include student.h if you access the Student class directly, whether or not you include graduateStudent.h. The #ifndef, which you installed in student.h, will make sure that the contents of student.h are not processed twice by the C++ compiler.

SeparatedMain is not a member of the Schools namespace. When main() refers to the Student class, C++ does not know whether the programmer intends to use the Student found in the Schools namespace or a similarly named class in some other namespace.

main() can completely specify a class without any possibility of ambiguity because Schools::Student refers specifically to the namespace and class. Alternatively, the programmer can specify her intentions at the beginning of the module: The phrase using Schools::GraduateStudent; tells C++ that any mention to GraduateStudent refers to the Schools namespace.

298 Part IV: Inheritance

The programmer can gain access to all members of the Schools namespace by adding the command using namespace Schools. The following version of main() builds successfully:

using namespace Schools;

int main(int nArgc, char* pszArgs[])

{

Student s(“Sophie Moore”, 1234);

cout << “Student = “ << s.display() << endl;

GraduateStudent gs(“Greg U. Waite”, 5678); cout << “Student = “ << gs.display() << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

You began using the using namespace std statement at the beginning of the book. The modules that make up the Standard C++ Library are members of the std namespace.

Project file

Full of expectation, I open the SeparatedMain.cpp file in the compiler and click Build. The module compiles properly, but an error occurs during the linking process. C++ does not know what a Student is. Somehow you have to tell C++ that the Student.cpp and GraduateStudent.cpp files need to be linked together with SeparatedMain.cpp to create the program. Most C++ environments, including both Dev-C++ and Visual C++.NET, combine multiple modules together via a project file.

Dev-C++ and Visual C++ use their own project file formats. The directions for creating a C++ console application project within Visual Studio.NET is pro­ vided on the enclosed CD-ROM in Bonus Chapter 2.

Creating a project file under Dev-C++

Execute the following steps to create a Dev-C++ project:

1.Choose File New Project. Select Console Application and type the name SeparateModules.

You should see the window in Figure 22-6.

Chapter 22: Factoring Classes 299

Figure 22-6:

The New Project window allows the user to enter the name and type of project.

2.Click OK.

Dev-C++ opens a file window.

3.Select the directory into which to store the project.

I selected \CPP_Programs\Chap22. Dev-C++ creates a project with a default initial module main.cpp.

4.Remove main.cpp from the project because you already have a main() module.

5.Choose Project Remove From Project.

6.Select main.cpp and click OK.

7.Copy the files main.cpp, Student.cpp, GraduateStudent.cpp, student.h, and graduateStudent.h to the Chap22 folder if they aren’t there already.

8.Choose Project Add to Project.

9.Select the entire list of source modules and click OK.

10.Choose Execute Rebuild All to compile the modules in the project and create an executable program.

11.Click the Classes tab in the left window to see a detailed description

of each class in the program, as shown in Figure 22-7.

Make sure that the class browser is enabled and configured properly.

300 Part IV: Inheritance

Figure 22-7:

The classes tab displays the members of each class.

Figure 22-8:

The class browser options tab determines the type of information available in the class browser.

12.Choose Tools Editor options and click the Class browsing tab.

13.Click the Enable Class Browser browser and the options shown in Figure 22-8.

Notice how the class browser displays each member. Functions display with their argument types as well as the type of object returned. Notice also that the class browser shows two display() member functions under the GraduateStudent class.

Chapter 22: Factoring Classes 301

14.Select the first display() entry in the list, the one with the small dia­ mond in front of it.

This opens the Student.cpp file and places the cursor on the display() member function. Selecting the second display() entry in the class browser takes the editor to the GraduateStudent::display() member function.

The properties of the project are initially set to the default. You can change the settings as follows.

15.Select Project Project Options.

For example, select the Linker options under the Compiler tab. Now make sure that Generate Debugging Information is set to Yes if you intend to use the Dev-C++ debugger.

I encourage you to break your programs into multiple source files. It simpli­ fies the editing, modifying, and debugging process.

302 Part IV: Inheritance

Part V

Optional Features

In this part . . .

The goal of this book is not to turn you into a C++ lan­ guage lawyer; it’s to give you a solid understanding of

the fundamentals of C++ and object-oriented programming.

The earlier parts in this book cover the essential features you need to know to produce a well-written, object-oriented C++ program. C++, however, is a big language (it has a seri­ ous case of feature-itis, if you ask me), and I have yet to discuss many features such as file input/output and the Standard Template Library. Part V rights this wrong.

C++ programmers have increasingly come to exploit the features of this library in the past few years. The BUDGET4 and BUDGET5 programs on the enclosed CD-ROM demon­ strate how.