Although a C++ programmer can use a header file to include any type of code in another file prior to compilation, they mainly use them to define a class. Typically programmers define a class interface in a header file and then write all of the class internal code in a separate source code file. In this way other programmers making use of the class directly or as part of a library need only the header file to inform themselves and the compiler how to use it. A simple class interface defined in a C++ header file can serve as both an example and a template for much larger more complex classes later.
Things Youll Need:
- Text or Code Editor
- Step 1
Create a new file named "MyClass.h." Enter the following three lines at the top of the file:
#ifndef _MYCLASS
#define _MYCLASS
#endif
The class will be defined between the line beginning with #define and the one beginning with #endif. These are preprocessor directives which tell the compiler to skip inclusion of this files contents if _MYCLASS has already been defined. If _MYCLASS is undefined, the compiler will define it and proceed to include the rest of the file. This prevents you from accidentally including a header file more than once, which can lead to conflicts and errors. - Step 2
Enter the following two lines after the line beginning with #define:
#include
using std::string;
This example class requires a string data type. The first directive includes the header file for the string class; the second statement simplifies its use by telling the compiler which namespace to make available. Rather than typing "std::string" everywhere, you use a string you can just type "string." - Step 3
Enter the following before the line with the #endif directive:
class MyClass
{
};
This defines an empty class. - Step 4
Fill the empty class by inserting the following lines within the opening and closing brackets:
public:
MyClass(string val);
void setVal(string val);
string getVal();
private:
string _myDataMember;
You have added one private class data member of type string and three public class method declarations: a constructor and two methods for accessing the data member. Task complete; class interface defined; C++ header file created. Most header files you will create or encounter will simply be more complex variations of this example
0 comments:
Post a Comment