Download presentation
Presentation is loading. Please wait.
Published byLewis Alvin Weaver Modified over 9 years ago
2
CHAPTER 8 USER-DEFINED SIMPLE DATA TYPES, NAMESPACES, AND THE string TYPE
3
In this chapter, you will: Learn how to create and manipulate your own simple data type—called the enumeration type Become aware of the typedef statement Learn about the namespace mechanism Explore the string data type, and learn how to use the various string functions to manipulate strings
4
ENUMERATION TYPE C++ allows the user to user defined simple data type, enumeration type. The syntax for enumeration type is: enum typeName{value1, value2,...}; where value1, value2, … are identifiers. Example enum colors{brown, blue, red, green, yellow}; brown has the value of 0,blue(1),red(2),green(3),yellow(4) //Illegal enumeration types enum grades{'A', 'B', 'C', 'D', 'F'}; enum places{1st, 2nd, 3rd, 4th}; Declaring Variables When Defining the Enumeration Type enum coins{penny, nickel, dime, halfDollar,dollar}change,usCoins; enum grades{A,B,C,D,F} courseGrade; Example 8-4 enum mathStudent{John, Bill, Cindy, Lisa, Ron}; enum compStudent{Susan, Cathy, John, William}; //Illegal Suppose that these statements are in the same program in the same block. The second enumeration type, compStudent, is not allowed because the value John was used in the previous enumeration type mathStudent.
5
Defining enumeration type enum sports{basketball, football, hockey,baseball, soccer,volleyball}; Declaring Variables sports popularSport, mySport; Assignment popularSport = football; mySport = popularSport; No arithmetic operation is allowed on enumeration type. mySport = popularSport + 2; //illegal popularSport = football + soccer; //illegal popularSport = popularSport * 2; // illegal Also, the increment and decrement operations are not allowed on enumeration types. The following statements are illegal; popularSport++; //illegal popularSport--; //illegal
6
Consider the following statements: popularSport = football; popularSport = static_cast (popularSport + 1); After the second statement, the value of popularSport will be hockey. The following statements results in storing basketball in popularSport. popularSport = football; popularSport = static_cast (popularSport - 1); Relational Operators football <= soccer is true hockey > basketball is true baseball < football is false Functions and Enumeration Types Enumeration type can be passed as parameters to functions either by value or by reference. A function can return a value of the enumeration type.
7
Example 8-5 enum courses{algebra, basic, pascal, cpp,philosophy, analysis, chemistry,history}; courses readCourses() { courses registered; char ch1,ch2; cin>>ch1>>ch2; //read two characters switch(ch1) { case 'a': if(ch2 == 'l') registered = algebra; else registered = analysis; break; case 'b': registered = basic; break; case 'c': if(ch2 == 'h') registered = chemistry; else registered = cpp; break; case 'h': registered = history; break; case 'p': if(ch2 == 'a') registered = pascal; else registered = philosophy; break; default: cout<<"Illegal input."<<endl; } return registered; } //end readCourses
8
Enumeration type can be output indirectly as follows: void printEnum(courses registered) { switch(registered) { case algebra: cout<<"algebra"; break; case analysis: cout<<"analysis"; break; case basic: cout<<"basic"; break; case chemistry: cout<<"chemistry"; break; case cpp: cout<<"cpp"; break; case history: cout<<history"; break; case pascal: cout<<"pascal"; break; case philosophy: cout<<"philosophy"; } //end switch } //end printEnum
9
Anonymous Data Types A data type in which values are directly specified in the variable declaration with no type name is called an anonymous type. enum {basketball, football, baseball, hockey} mysport; Creating an anonymous type has drawbacks. We cannot pass an anonymous type as a parameter to a function. A function cannot return a value of an anonymous type. Values used in one anonymous type can be used in another anonymous type, but variables of those types are treated differently. enum {English, French, Spanish, German, Russian} languages; enum {English, French, Spanish, German, Russian} foreignLanguages; languages = foreignLanguages; //illegal
10
The typedef Statement In C++, you can create synonyms or aliases to a previously defined data type by using the typedef statement. Example 8-6 The following statement creates an alias, integer, for the data type int. typedef int integer; The following statement creates an alias, real, for the data type double. typedef double real; Example 8-7 typedef int Boolean;//Line 1 const Boolean True = 1; //Line 2 const Boolean False = 0; //Line 3 Boolean flag;//Line 4 flag = True;
11
In July 1998, ANSI/ISO standard C++ was officially approved. Most of the recent compilers are also compatible with ANSI/ISO standard C++. In previous chapters, we mainly dealt with standard C++ and briefly introduced the features of ANSI/ISO standard C++. For most part the two standards are the same. In this chapter, we discuss some of the features of ANSI/ISO standard C++ language that are not available in standard C++. Namespaces When a header file, such as iostream, is included in a program, the global identifiers in the header file also become the global identifiers in the program. If a global identifier in a program has the same name as one of the global identifiers in the header file, the compiler will generate syntax error (such as identifier redefined). The same problem can occur if a program uses third party libraries. To overcome this problem, third party vendors begin their global identifiers with a special symbol. Since compiler vendors begin their global identifier with _ (under score), to avoid linking errors do not begin identifiers in your program with _ (under score). ANSI/ISO standard C++ attempts to solve this problem of overlapping global identifier names with the namespace mechanism.
12
Example 8-8 namespace globalType { const int n = 10; const double rate = 7.50; int count = 0; void printResult(); } defines globalType to be a namespace with four members. The scope of a namespace member is local to the namespace. There are usually two ways a namespace member can be accessed outside the namespace. To access the member rate of the namespace globalType, the following statement is required: globalType::rate To access the member printResult (which is a function), the following statement is required: globalType::printResult(); To simplify the accessing of a namespace member, C++ provides the use of the statement using. Syntax: using (a) To simplify the accessing of all namespace members: using namespace namespace_name; ( b) To simplify the accessing of a specific namespace member: using namespace_name::identifier;
13
Example 8-12 include using namespace std; int t; double u; namespace exp {int x; char t; double u; void printResult(); } using namespace exp; int main() { int one; double t; double three; //To access global t in main, we use ::t //To access t within namespace “exp”, use exp::t //To access x from “exp”, you can use x or exp::x //To call function printResult, use printResult() or exp::printResult() } void exp::printResult() {. }
14
The using statement using namespace globalType; simplifies the accessing of all members of the namespace globalType The statement using globalType::rate; simplifies the accessing of the member rate of the namespace globalType. In C++, using is a reserved word. The using statement is usually put after the namespace declaration. After the using statement, to access a namespace member it is not necessary to precede the namespace_name and the scope resolution operator before the namespace member. If a namespace member and a global identifier in a program have the same name, to access this namespace member in the program, the namespace_name and the scope resolution operator must precede the namespace member. If a namespace member and an identifier in a block have the same name, to access this namespace member in the block, the namespace_name and the scope resolution operator precedes the namespace member.
15
Example 8-9 #include using namespace std;. int main() {. }. In this example, we can refer to global identifiers of the header file iostream, such as cin, cout, and endl, without using the prefix std:: before the identifier name. The obvious restriction is that the block (or the function) where the global identifier (of the header file iostream ) is referred must not contain any identifier with the same name as this global identifier. Example 8-11 #include. int main() { using namespace std;. }. In this example, the function main can refer to the global identifiers of the header file iostream without using the prefix std:: before the identifier name. Since the using statement appears inside the function main, other functions (if any) should use the prefix std:: before the name of the global identifier of the header file iostream unless the function also has a similar using statement.
16
The string Type To use the data type string, the program must include the header file string #include The statement string str1= "Hello there”, str2, str3; declares str1,str2 and str3 to be string variable and also initializes str1 to " Hello there ". The position of the first character, H, in str1 is 0, the position of the second character, ’e', is 1, and so on. Each string variable is capable of storing (just about) any size string. Binary operator + (to allow the string concatenation operation), and the array index (subscript) operator [], have been defined for the data type string. str2 = “Day” str3 = str1 + ”. ” + “Sunny” + ‘ ‘ + str2; stores the string ”Hello there. Sunny Day" into str3. str1[6] = 'T'; replaces the character t with the character T.
17
The data type string has a data type, string::size_type, and a named constant, string::npos, associated with it. string::size_type An unsigned integer (data) type string::npos The maximum value of the (data) type string::size_type, a number such as 4294967295 on many machines
18
The length Function The length function returns the number of characters currently in the string. The value returned is an unsigned integer. The syntax to call the length function is: strVar.length() where strVar is variable of the type string. The function length has no arguments. String name = “Wojciechowski”; name.length() would return 13
19
The size Function The function size is same as the function length. Both these functions return the same value. The syntax to call the function size is: strVar.size() where strVar is variable of the type string. As in the case of the function length, the function size has no arguments.
20
The find Function The find function searches a string to find the first occurrence of a particular substring and returns an unsigned integer value (of type string::size_type ) giving the result of the search. The syntax to call the function find is: strVar.find(strExp) where strVar is a string variable and strExp is a string expression evaluating to a string. The string expression, strExp, can also be a character. If the search is successful, the function find returns the position in strVar where the match begins. For the search to be successful, the match must be exact. If the search is unsuccessful, the function returns the special value string::npos ( “not a position within the string”). string sentence,str; string::size_type position; sentence = "It is cloudy and warm."; str = "cloudy"; StatementEffect cout<<sentence.find("is")<<endl; Outputs 3 cout<<sentence.find('s')<<endl; Outputs 4 cout<<sentence.find(str)<<endl; Outputs 6 position = sentence.find("warm"); Assigns 17 to position
21
The substr Function The substr function returns a particular substring of a string. The syntax to call the function substr is: strVar.substr(expr1,expr2) where expr1 and expr2 are expressions evaluating to unsigned integers. The expression expr1 specifies a position within the string (starting position of the substring). The expression expr2 specifies the length of the substring to be returned.
22
string sentence; stringstr; sentence = "It is cloudy and warm."; Statement Effect cout<<sentence.substr(0,5) Outputs: It is <<endl; cout<<sentence.substr(6,6) Outputs: cloudy <<endl; cout<<sentence.substr(6,16) Outputs: cloudy and warm. <<endl; cout<<sentence.substr(3,6) Outputs: is clo <<endl; str = sentence.substr(0,8); str = "It is cl" str = sentence.substr(2,10); str = " is cloudy"
23
The Function swap The function swap is used to swap—that is, interchange—the contents of two string variables. The syntax to use the function swap is strVar1.swap(strVar2) ; where strVar1 and strVar2 are string variables. Suppose you have the following statements: string str1 = "Warm"; string str2 = "Cold"; After the following statement executes, the value of str1 is "Cold" and the value of str2 is "Warm". str1.swap(str2);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.