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

Chapter 25

. . . Write to a File

The following program outputs a message to a file, then reopens the file and appends another message. Additional details can be found in Chapter 14.

/**

* writefile.cpp */

#include <iostream> #include <fstream>

using namespace std;

int main()

{

ofstream outFile(“writefile.out”);

if (outFile.fail()) {

cerr << “Unable to open file for writing.” << endl; exit(1);

}

outFile << “Hello!” << endl;

outFile.close();

ofstream appendFile(“writefile.out”, ios_base::app);

if (appendFile.fail()) {

cerr << “Unable to open file for writing.” << endl; exit(1);

}

appendFile << “Append!” << endl;

appendFile.close();

}

. . . Write a Template Class

Template syntax is one of the messiest parts of the C++ language. The most-forgotten piece of the template puzzle is that code that uses the template needs to be able to see the method implementations as well as the class template definition. The usual technique to accomplish this is to #include the source file in the header file so that clients can simply #include the header file as they normally do. The following program shows a class template that simply wraps an object and adds get and set semantics to it.

/**

* SimpleTemplate.h */

template <typename T> class SimpleTemplate

{

734

Incorporating Techniques and Frameworks

public:

SimpleTemplate(T& inObject);

const T& get();

void set(T& inObject);

protected:

T& mObject;

};

#include “SimpleTemplate.cpp” // Include the implementation!

/**

* SimpleTemplate.cpp */

template<typename T>

SimpleTemplate<T>::SimpleTemplate(T& inObject) : mObject(inObject)

{

}

template<typename T>

const T& SimpleTemplate<T>::get()

{

return mObject;

}

template<typename T>

void SimpleTemplate<T>::set(T& inObject)

{

mObject = inObject;

}

/**

* TemplateTest.cpp */

#include <iostream> #include <string>

#include “SimpleTemplate.h”

using namespace std;

int main(int argc, char** argv)

{

//Try wrapping an integer. int i = 7;

SimpleTemplate<int> intWrapper(i); i = 2;

cout << “wrapper value is “ << intWrapper.get() << endl;

//Try wrapping a string.

string str = “test”;

735