1 / 31

Topic 5 - User Defined Header Files – User Defined Data Types

Topic 5 - User Defined Header Files – User Defined Data Types. Header Files, Enumerated Types & Typedefs. User Defined Header Files. Part 1. Header files. So far we’ve worked with several header files files that follow #include < iostream > < iomanip > < fstream > <string>

pascha
Télécharger la présentation

Topic 5 - User Defined Header Files – User Defined Data Types

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Topic 5 - User Defined Header Files – User Defined Data Types Header Files, Enumerated Types & Typedefs

  2. User Defined Header Files Part 1

  3. Header files • So far we’ve worked with several header files • files that follow #include • <iostream> • <iomanip> • <fstream> • <string> • We include these to be able to access certain predefined functions, classes, or variables in C++

  4. Creating our own • It is often convenient to create your own header files • To do this we need to • create the file • Include it in our source code • Creating the file • create a new file filename.h • end it with .h • Including the file • #include “filename.h”

  5. Header File // these two lines and the last one ensure that you // don’t accidentally make the same definitions twice – it is a good // practice to include them // this example assumes your header file name is MyHeader.h #ifndef MYHEADER_H_ #define MYHEADER_H_ <your preprocessor directives> <global consants> <your typedefs and enumerated types> <your function prototypes> #endif We will discuss these later • NOTE: • eclipse will automatically include the lines of code that are in black •  you MUST insert your preprocessor directives, tyedefs, • and enumerated types as specified

  6. Example: Creating a header file // this file is called myheader.h #ifndef MYHEADER_H_ #define MYHEADER_H_ // preprocessor directives go here #include <iostream> #include <iomanip> #include <string> using namespace std; // Global Constants // User Defined Types go here (more on this later) // Prototypes go here intSearchStArray(string stAr[], string searchStr); #endif /* MYHEADER_H_ */ • To include this file #include “MyHeader.h”

  7. Some points to mention • you must use quotes in your header file • “MyHeader.h” NOT <MyHeader.h> • the file must be located in your project folder • otherwise C++ can’t find it

  8. How to include source code • Create the file as a source file (.cpp) • add your code (make sure you use the headers that you need) • put the source file in the same folder as your main.cpp • Don’t #include for source code

  9. Common Errors • Make sure your files are all in the same folder • Make sure that you have your preprocessor directives BEFORE your prototypes • ORDER MATTERS • 1 – preprocessor directives • # includes & namespace • 2 – global constants • 3 – typedefs and enumerated types • 4– prototypes • You can’t have code in the header file • You can have code in a separate file • You can only have 1 int main()

  10. Good Practices • Keep related functions in the same files • e.g. I/O • Separating your files makes them easier to manage • your main.cpp can get long and difficult to find things

  11. Some notes on Functions • Keep them simple and try to make them generic  that way you can reuse them Example: // this function searches a string array for one string // returns the appropriate index # intSearchStringArray(const string STR_AR[] , const int AR_SIZE, string searchStr) Instead of intSearchName(const string NAME_AR[], const int AR_SIZE, string searchName) • Keep them Simple! • each function should do 1 thing • In otherwords if you need to search for something your function should just search for that something not deal with I/O specific to your project

  12. Enumerated Types

  13. floating address float double long double pointer reference C++ Data Types simple structured integral enum array structunion class char short int long bool

  14. C++ Simple Data Types

  15. Data types • So far the simple data types we’ve worked with have been • int to store integers • float to storefloating point numbers • char to store a character (or a c-string) • bool to store T or F (1 or 0) • We can use these to solve many problems but… What if we need to create a different data type specifically for our program

  16. Enumeration Type Let’s say we want a program that works with the days of the week  there is no days data type Enumeration Types allow us to create our own data type To Define an enumeration type we need • a name for the data type • a set of values for the data type • a set of operations on the values • Using enumerated types are self-documenting • they make your code more understandable • Syntax • enumTypeName{value1, value2, value3, …};

  17. Defining a Enumeration Type Let’s say we want to define the days of the week enumDays { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; What we have done is defined Days now as adatatypethat can only take the values we have specified. This is our new type Capitalize the first letter These are the values that Days can take

  18. Example // now we can assign any of the // values we specified to // our variable today today = MONDAY; if (today == SUNDAY || today == SATURDAY) { cout << “\nGotta love the weekends!\n”; } else { cout << “\nBack to work.\n”; } return 0; } #include <iostream> int main() { enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; // this will declare a // variable today // of type Days Days today;

  19. How does it work? • Enumerated type Days is defined with 7 values • Each evaluates to an integer (0-6) • We could instead have declared each day as a constant const int SUNDAY = 0; const int MONDAY = 1; …

  20. Enum Values • Enumeration values must be legal identifiers • These are illegal • enum Grades {‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; • enum Places {1st, 2nd, 3rd, 4th, 5th}; • These are legal • enum Grades {A,B,C,D,F}; • enum Places {FIRST, SECOND, THIRD, FOURTH, FIFTH} • CAN’T assign the same value to 2 enum types • enumMathStudent {JOHN, BILL, LISA}; • enumCompStudent {SUSAN, LISA, JOE};

  21. Because they evaluate to numbers • You CAN compare the values • today < eventDay … and you CAN assign them to each other • today = eventDay • But you CAN’T do arithmetic and assign it back into your enum type • today = eventDay - 3 • today++ …although you CAN type cast them • today = days(today + 1); … or assign the result into an in • intVar = today – eventday;

  22. Example on Enums (1) Days today; Days eventDay; today = MONDAY; eventDay = FRIDAY; if (today < eventDay ) { cout << "You're event is in " << eventDay - today << " days"; } else if (today == eventDay) { cout << "Today is the day!"; } else { cout << "You missed it!"; }

  23. Example on Enums (2) Days today; Days eventDay; intdaysToEvent; today = MONDAY; eventDay = FRIDAY; if (today < eventDay ) { daysToEvent = eventDay – today; cout << "You're event is in " << daysToEvent << " days"; } else if (today == eventDay) { cout << "Today is the day!"; } else { cout << "You missed it!"; }

  24. Example on Enums (3) Days today; Days eventDay; Days daysToEvent; today = MONDAY; eventDay = FRIDAY; if (today < eventDay ) { daysToEvent = days(eventDay – today); cout << "You're event is in " << daysToEvent << " days"; } else if (today == eventDay) { cout << "Today is the day!"; } else { cout << "You missed it!"; }

  25. Input / Output of Enum Types • Enum types CAN’T be input or output directly string inputDay; Days today; cout << “What day is it?”; cin >> inputDay; switch (toupper(inputDay[0]) { case ‘S’: if (toupper(inputDay[1])=‘A’) today = SATURDAY; else today = SUNDAY; break; case ‘M’: today = MONDAY; break; case ‘W’: today = WEDNESDAY; … Now you write the code to output the day for the variable today

  26. Output an Enum Type Days today; switch (today) {

  27. typedef

  28. typedef • typedef creates an additional name for an already existing data type Examples: typedefintInteger; typedef float Real; typedef double BigReal; • Syntax • typedefexistingTypeNameNewTypeName;

  29. Example: typedef • before the bool type became a part of ISO-ANSI C++ you could simulate a Boolean type using typedef typedefint Boolean; const Boolean TRUE = 1; const Boolean FALSE = 0; … Boolean dataOK; … dataOk = TRUE;

  30. Example #2: typedef typedef float FloatArrayType[100]; • anything of type FloatArrayType is defined as a 100 element array of float values FloatArrayTypemyArray; • MyArray is a variable representing a 100 element array of float values • If you make your typedefs global you can use them as parameters void LoadArray(FloatArrayTypeanArray)

  31. Don’t forget where they go in Header Files #ifndef MYHEADER_H_ #define MYHEADER_H_ // preprocessor directives go here #include <iostream> #include <iomanip> #include <string> using namespace std; // typedefs and enums go here enum Color { RED, BLUE, GREEN }; typedef float SalesArrayType[7]; // Prototypes go here void LoadSales(SalesArrayType sales); #endif /* MYHEADER_H_ */ ”

More Related