[go: up one dir, main page]

Academia.eduAcademia.edu

Tutorial

cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: The online version is constantly revised and may contain corrections and changes The C++ Language Tutorial This document and its content is copyright of cplusplus.com © cplusplus.com, 2008. All rights reserved. Any redistribution or reproduction of part or all of the content in any form is prohibited other than to print a personal copy of the entire document or download it to a local hard disk, without modifying its content in any way (including, but not limited to, this copyright notice). You may not, except with express written permission from cplusplus.com, distribute the content of this document. Nor may you transmit it or store it in any other website or other form of electronic retrieval system. The C++ Language Tutorial Table of contents Table of contents ...............................................................................................................................3 Introduction ......................................................................................................................................5 Instructions for use ................................................................................................................................... 5 Basics of C++ ......................................................................................................................................7 Structure of a program ............................................................................................................................. 7 Variables. Data Types. ............................................................................................................................. 11 Constants ................................................................................................................................................ 17 Operators ................................................................................................................................................ 21 Basic Input/Output.................................................................................................................................. 29 Control Structures ............................................................................................................................ 34 Control Structures ................................................................................................................................... 34 Functions (I) ............................................................................................................................................ 41 Functions (II) ........................................................................................................................................... 47 Compound data types ...................................................................................................................... 54 Arrays ...................................................................................................................................................... 54 Character Sequences .............................................................................................................................. 60 Pointers ................................................................................................................................................... 63 Dynamic Memory.................................................................................................................................... 74 Data structures........................................................................................................................................ 77 Other Data Types .................................................................................................................................... 82 Object Oriented Programming.......................................................................................................... 86 Classes (I)................................................................................................................................................. 86 Classes (II) ............................................................................................................................................... 95 Friendship and inheritance ................................................................................................................... 100 Polymorphism ....................................................................................................................................... 107 Advanced concepts ........................................................................................................................ 113 Templates.............................................................................................................................................. 113 Namespaces .......................................................................................................................................... 120 Exceptions ............................................................................................................................................. 123 Type Casting .......................................................................................................................................... 127 The C++ Language Tutorial Preprocessor directives......................................................................................................................... 133 C++ Standard Library ...................................................................................................................... 138 Input/Output with files ......................................................................................................................... 138 The C++ Language Tutorial Introduction ! " # " ! ! $ $ % ! & '()"& * + $ , ! $ # " $ $ ' $ $ ! . . $ / '()"& ( " 0112! 33 ( ! $ '()"& & " $ 40153 6 ! & '()"& ! $ " The C++ Language Tutorial ' . * The C++ Language Tutorial Basics of C++ 7 ! 8 // my first program in C++ Hello World! #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } $ - " ! 9: ; /9 " ! ; % 8 ' 4//6 $ " < ! 4#6 $ <iostream> . " 4 & #include 6 ! ' ! ) $ # $ ! ! " & . = main 8" $ ! main 4()6 ! $ ! > 4{}6 ; $ 2 The C++ Language Tutorial ' " $ ! cout # ! Hello World 4 4 # 6 6 cout iostream ! std ( . 4;6 $ 4 $ 6 4 $ 06 ' 3 $ $ + $ 4 . //6 4 4 #6 6 ! 4 ! cout6! 4{}6 ! = $ ! ! int main () { cout << " Hello World!"; return 0; } ; 8 int main () { cout << "Hello World!"; return 0; } ' " % $ ! 4;6 ; < 8 5 ! The C++ Language Tutorial // my second program in C++ Hello World! I'm a C++ program #include <iostream> using namespace std; int main () { cout << "Hello World! "; cout << "I'm a C++ program"; return 0; } " ! % ! main ! 8 int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; } ; 8 int main () { cout << "Hello World!"; cout << "I'm a C++ program"; return 0; } ' $ 7 $ 4 #6 7 4;6 8 // line comment /* block comment */ ! ! 4//6 ! */ ; ! ! 8 1 /* The C++ Language Tutorial /* my second program in C++ with more comments */ Hello World! I'm a C++ program #include <iostream> using namespace std; int main () { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0; } " //! /* $ */! 03 ! The C++ Language Tutorial 9: ; 9 ! ! # $ # ; % " : ! $ < " " ! + 0 " " ? % ( ! *4 06 ! " @ $ % $ 8 a = 5; b = 2; a = a + 1; result = a . b; ! $ ! ! A ! a! b ' $ ! ! result! # ! 4_6 ( ! " ! 4_ 6! $ ! " ' . ! 8 asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while ' ! 8 and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq 00 The C++ Language Tutorial + 9 9 # ! RESULT result ; $ ! Result ! . ! ! ! ? ' ' 8 4 3 6 " ! $ ! & ( $ ! 8 ! " char # " 8 &0 5 0 2 83 8 & 2*5 2*2 83 * 8& 0 2 5 * 5 0 2 5 * 2 83 1 1*2 1 8& 0 2 5 * 5 0 2 5 * 2 83 1 1*2 1 0 short int 4short6 ) int " " long int 4long6 < B bool float double long double = < wchar_t ; " 8 C& C& 0 2 C& 0 2 5 5 C& 5 4D2 C& 35 4D0 C& 35 4D0 6 6 6 0 E ! # & B ? int 0 ! 4 long float! double 9 int char! short! 0 ? 96 ! char long double! $ " ! $ 4 = $ 8 0 ! ! 6 The C++ Language Tutorial int a; float mynumber; float int ! mynumber a a mynumber " = ! 8 $ int a, b, c; 4a! b c6! $ int! 8 int a; int b; int c; char! short! long ) int ! 4 signed ? = unsigned 6 $ 8 unsigned short int NumberOfSisters; signed int MyAccountBalance; B ! signed unsigned ! 8 int MyAccountBalance; $ ' 4 $ signed6 char ! unsigned char! signed char + signed char& ? unsigned short $ " long 8 short # # ! short int long # long int 8 short Year; short int Year; = ! signed unsigned unsigned int # ! 8 unsigned NextYear; unsigned int NextYear; ! $ 8 0 signed int The C++ Language Tutorial // operating with variables 4 #include <iostream> using namespace std; int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a . b; // print out the result: cout << result; // terminate the program: return 0; } - + $ ' ! a! b! result int ' ' ! ! F ! 0 ! The C++ Language Tutorial 4GH6 4 " main! = $ ! $ ; ! B " ! ? 8 ? ! 8 & ! # type identifier = initial_value ; = $ ! ? ! 3 8 int a = 0; ? 4()68 ! ? ! type identifier (initial_value) ; = $ 8 int a (0); B ? # // initialization of variables 6 #include <iostream> using namespace std; int main () { int a=5; int b(2); int result; undetermined // initial value = 5 // initial value = 2 // initial value a = a + 3; result = a . b; cout << result; return 0; } @ & string ! 0 ! $ main ! $ main6 The C++ Language Tutorial ' % 8 <string> using namespace 4 // my first string #include <iostream> #include <string> using namespace std; 4 6 std 6 This is a string int main () { string mystring = "This is a string"; cout << mystring; return 0; } ' $ ! ? B ? % ? 8 string mystring = "This is a string"; string mystring ("This is a string"); ) ! $ 8 // my first string #include <iostream> #include <string> using namespace std; int main () { string mystring; mystring = "This cout << mystring mystring = "This cout << mystring return 0; } = is << is << This is the initial string content This is a different string content the initial string content"; endl; a different string content"; endl; ! 0* The C++ Language Tutorial $ $ % < $ ; $ $ ! ! 8 a = 5; 5 < @ " ( != &7 ( ! !) B 1776 707 .273 ( # 8 ! 1776 022* " 4 4 0x 4? 75 0113 0x4b 6 56 0 4? ! $6 = $ $ 4 6 ' ! 0*6 " $ $ $ # 8 // decimal // octal // hexadecimal ' 82 4 $ & 6 $ &03 ! ! < int : ! ! B ! 75 75u 75l 75ul " 4 $ 4"6 // // // // ! l8 int unsigned int long unsigned long ! $ $ ! u $ 9 C 9! I e $ ! I e 8 02 e 6! The C++ Language Tutorial 3.14159 6.02e23 1.6e.19 3.0 // // // // 3.14159 6.02 x 10^23 1.6 x 10^.19 3.0 $ ' $ 7"! ! 4 & $ ! 3.14159L 6.02e23f f 6& & double " $ l $ $ 8 $ float long double // long double // float ' & $ & ! 4e! f! l6 8 'z' 'p' "Hello world" "How do you do?" $ ! ( $ # 4 4'6 6 # 4"6 ; ! # ( $ 8 x 'x' x 'x' 4 x! # 6 'x' ! $ ! 4\6 : 05 4\n6 8 4\t6 ' The C++ Language Tutorial \n \r \t \v \b \f 4 \a 4 \' # \" 6 6 4'6 # 4"6 \? # 4?6 \\ 4\6 = $ 8 '\n' '\t' "Left \t Right" "one\ntwo\nthree" ' ! $ ') "" 4 4 $ 4 &56 4 6 $ 6! ) ') "" $ $ 4\6 4 \23 x &0*6 \406! 4 $ " \x20 $ \x4A6 4\6 "string expressed in \ two lines" + ! ! 8 "this forms" "a single" "string" "of characters" = ! 4char6! $ 4wchar_t6! < $8 L"This is a wide character string" ; &A B true B $ 8 false $ &' bool ( + & ! " #define 01 8 The C++ Language Tutorial #define identifier value = $ 8 #define PI 3.14159 #define NEWLINE '\n' 8 PI NEWLINE ! $ ! 8 // defined constants: calculate circumference 31.4159 #include <iostream> using namespace std; #define PI 3.14159 #define NEWLINE '\n' int main () { double r=5.0; double circle; // radius circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; } " 4 43.14159 $ #define PI NEWLINE6 ! 6 '\n' J #define # 4;6 " 4;6 ! & ; const ( $ 8 const int pathwidth = 100; const char tabulator = '\t'; : ! pathwidth % tabulator 3 $ The C++ Language Tutorial ) $ ! = K ! + A ! ? * ! ! # , &+( a = 5; 4=6 a 4 6 4 ! 6 ! 8 ! 8 a = b; a4 6 b4 b b = $ 6 ! a a a ! &" 8 // assignment operator a:4 b:7 #include <iostream> using namespace std; int main () { int a, b; a = 10; b = 4; a = b; b = 7; cout cout cout cout << << << << // // // // // a:?, a:10, a:10, a:4, a:4, b:? b:? b:4 b:4 b:7 "a:"; a; " b:"; b; return 0; } a b! 4 b a = b 6 0 4 7 ( a The C++ Language Tutorial ' 4 6 = $ 8 a = 2 + (b = 5); # 8 b = 5; a = 2 + b; 8 6! b4 5 b a a 2 7 $ 8 a = b = c = 5; " 8 a! b 5 * c & ,- .- "- /- 0 ( 8 & E C L ! ! J 4%6 , = $ ! 8 a = 11 % 3; a 2! 2 11 3 &,+- .+- "+- /+- 0+- 11+- 22+- 3+4+- 5+( ; 8 6 value += increase; value a .= 5; a = a a /= b; a = a price *= units + 1; price = . / = 7 $ value + increase; 5; b; price * (units + 1); = $ 8 The C++ Language Tutorial // compound assignment operators 5 #include <iostream> using namespace std; int main () { int a, b=3; a = b; a+=2; cout << a; return 0; } // equivalent to a=a+2 &,,- ..( ) $ ! 4++6 # 4..6 +=1 8 .=1! c++; c+=1; c=c+1; # 8 " ! ( $ $ ! ? $ ! $ $ ' $ $ 4++a6 $ ! $ $ 4a++6 ' $ a++ ++a 8" $4 6 $ $ J $ 4a++6 $ ( 8 86 9 86 : B=3; B=3; A=++B; A=B++; // A contains 4, B contains 4 // A contains 3, B contains 4 " A$ B 0! B # A ; 7 A$ ! B & ++- ;+- 1- 2- 1+- 2+ ( " $ # B ; $ : A ! ! $ # ! B # 8 The C++ Language Tutorial MM A# /M ( N F O < NM F OM < # # # : $ (7 (5 (3 (6 (5 == 5) > 4) != 2) >= 6) < 5) // // // // // ! a=2! b=3 evaluates evaluates evaluates evaluates evaluates to to to to to false. true. true. true. false. ! $ // // // // evaluates evaluates evaluates evaluates / =4 to to to to ) false since a is not equal to 5. true since (2*3 >= 6) is true. false since (3+4 > 2*6) is false. true. # 6 == 4 6 # 4 $ $ ! c=6! (a == 5) (a*b >= c) (b+4 > a*c) ((b=2) == a) B 8 ((b=2) == a)! 2 # 6! 4==6 # ! b a! 2! % & ;- 33- 55 ( B ! ( ! ! ! ! B !(5 == 5) !(6 <= 4) !true !false ! // // // // evaluates evaluates evaluates evaluates && && B to to to to = $ 8 false because the expression at its right (5 == 5) is true. true because (6 <= 4) would be false. false true. $ || B '(- ! $ && a && b8 33 )<8#* )# 33 B || ! || b8 > : a The C++ Language Tutorial 55 )<8#* )# 55 = $ 8 ( (5 == 5) && (3 > 6) ) ( (5 == 5) || (3 > 6) ) // evaluates to false ( true && false ). // evaluates to true ( true || false ). & ( $ $ $ " 8 condition ? result1 : result2 " condition $ 7==5 ? 4 : 3 7==5+2 ? 4 : 3 5>3 ? a : b a>b ? a : b // // // // result1! returns returns returns returns result2 3, since 7 is not equal to 5. 4, since 7 is equal to 5+2. the value of a, since 5 is greater than 3. whichever is greater, a or b. // conditional operator 7 #include <iostream> using namespace std; int main () { int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c; return 0; } " $ a 2 b 7! $ 4a>b6 4 # ! 6 b! 7 &-( 4,6 $ = ; $ ! a = (b=3, b+2); $ $ $ ! 8 $ The C++ Language Tutorial ; 3 5 b! = a ) ! b+2 b ! a 3 ) & 3- 5- 4- >- 22- 11 ( B 7 & | ^ ~ << >> $ '(> I > ( ):< ):> B B B K ) ) '(" A$ > > 4 6 < > 86 ! ! $ 4()68 int i; float f = 3.14; i = (int) f; 436! 3.14 : ! (int) ' 8 $ $ 8 i = int ( f ); B ! &( ! ? % 8 a = sizeof (char); 1 sizeof char ! & $ ) < ! % & ! A < ; $ $ ! = $ ! $ 8 a = 5 + 7 % 2 * The C++ Language Tutorial 8 a = 5 + (7 % 2) a = (5 + 7) % 2 // with a result of 6, or // with a result of 0 $ ! 6 ! 4 6 = % $ 0 ! 8 ) ? < & & :: () [] . .> ++ .. dynamic_cast static_cast reinterpret_cast const_cast typeid ++ .. ~ ! sizeof new delete < $ 4 * & 4 & & $6 > & & > & & 6 + . (type) .* .>* & & * * / % 2 + . 5 << >> 1 < > <= >= 03 == != 00 & '(- 0 ^ I > 0 | > 0 && '(- 0 || > 0* ?: 02 = *= /= %= += .= >>= <<= &= ^= |= 05 , # < & & < & & < & & < & & < & & < & & < & & < & & < & & < & & < & & > & & > & & < F $ ' ( )! $ 8 a = 5 + 7 % 2; 2 & & The C++ Language Tutorial 8 a = 5 + (7 % 2); a = (5 + 7) % 2; ) $ ! " 5 The C++ Language Tutorial = /) K K ! $ ! ! . # ' C % $ ; & # % iostream! ) B & ( ! ! % cout % ! << 4 cout 9 9 6 cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen " x # << Output sentence! 120 ( $ cout 4"6 ; # 4"6 = $ ! 8 cout << "Hello"; cout << Hello; // prints Hello // prints the content of Hello variable 4<<6 8 cout << "Hello, " << "I am " << "a C++ statement"; Hello, I am a C++ statement 4<<6 8 cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode; " age 24 zipcode 90064 8 Hello, I am 24 years old and my zipcode is 90064 " $ cout ! 8 1 ! The C++ Language Tutorial cout << "This is a sentence."; cout << "This is another sentence."; 8 This is a sentence.This is another sentence. cout " $ 4 & cout " & \n ! 68 cout << "First sentence.\n "; cout << "Second sentence.\nThird sentence."; 8 First sentence. Second sentence. Third sentence. ' ! & ! = endl $ 8 cout << "First sentence." << endl; cout << "Second sentence." << endl; 8 First sentence. Second sentence. ! $ endl '\n' ' 8 ! & ! ! cout \n endl ( : $ 4>>6 $ cin = $ 8 int age; cin >> age; int cin 4 age! 6 cin # ! RETURN RETURN ! $ cin + cin $ # ! # 3 " # The C++ Language Tutorial // i/o example Please enter an integer value: 702 The value you entered is 702 and its double is 1404. #include <iostream> using namespace std; int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; } cin 4 % $ 6 ) 6! # 4 ) cin $ C # + ' C stringstream ! # 8 cin >> a >> b; # 8 cin >> a; cin >> b; " ! 8 ; : a $ cin cin >> mystring; ! 4>>6 ! cin $ % $ " ! b ! 8 ! $ ! J $ getline! cin8 0 The C++ Language Tutorial // cin with strings #include <iostream> #include <string> using namespace std; What's your name? Juan SouliÃ‾¿½ Hello Juan SouliÃ‾¿½. What is your favorite team? The Isotopes I like The Isotopes too! int main () { string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0; } ( 4mystr6 ; getline <sstream> & stringstream $ C = $ ! % ! $ 8 string mystr ("1204"); int myint; stringstream(mystr) >> myint; % string % ! "1204"! % $ 4>>6 int B % stringstream. stringstream % cin $ int ' ! myint // stringstreams #include <iostream> #include <string> #include <sstream> using namespace std; 1204 Enter price: 22.25 Enter quantity: 7 Total price: 155.75 int main () { string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); stringstream(mystr) >> price; cout << "Enter quantity: "; getline (cin,mystr); stringstream(mystr) >> quantity; cout << "Total price: " << price*quantity << endl; return 0; } " $ ! # ! $ " 4cin6 4quantity6 $ % 4mystr6! The C++ Language Tutorial K ! $ ! ! 6 4 ! The C++ Language Tutorial Control Structures ' # = - ! ! ! ; 8 ' 4J6 ! 8 { }8 { statement1; statement2; statement3; } , # $ ' 4 6 4 6! % ! $ if " 4{}6 B 4{}6! " 8 if (condition) statement ; = condition ! statement $ ! $ " 4 $ ! statement $ " 6 x is 100 x 1008 if (x == 100) cout << "x is 100"; " $ { }8 if (x == 100) { cout << "x is "; cout << x; } ; else " % if 8 if (condition) statement1 else statement2 = $ 8 The C++ Language Tutorial if (x == 100) cout << "x is 100"; else cout << "x is not 100"; x is 100 x & 100! & x is not 100 if + else $ x if (x > 0) cout << "x else if (x < cout << "x else cout << "x ! 4 ? 68 is positive"; 0) is negative"; is 0"; > $ ! { } & ( < " 8 while (expression) statement $ = $ ! & // custom countdown using while 8 Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; ..n; } cout << "FIRE!\n"; return 0; } ; while ! $ n>0 4 n 4n>06 ? 6 4 68 The C++ Language Tutorial 0 K n E E 4n>06 ' $ 8 8 8 4 6 4 A$ 8 cout << n << ", "; ..n; 4 n A n 6 16 > 8 ; & =">A/ ! ! ! " ..n; 4n6 & 4n>06 8 " ! n & 0! 8 do statement while (condition); " $ ! $ $ = $ condition $ ! $ ! // number echoer Enter number You entered: Enter number You entered: Enter number You entered: #include <iostream> using namespace std; int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; } & statement (0 to end): 12345 12345 (0 to end): 160277 160277 (0 to end): 0 0 & ! ! " " 0 8 for (initialization; condition; increase) statement; * $ condition 0 The C++ Language Tutorial statement " ! condition initialization for B ! ) increase ? 8 0 $ initialization F $ " condition 4 $ ! $ statement ' ! ! : statement 6 { } $ increase $ 8 // countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n..) { cout << n << ", "; } cout << "FIRE!\n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! J ! ! for increase = $ for (;n<10;n++) ? ! initialization initialization! $ 8 for (;n<10;) ? ? 4 6 4,6 $ $ 4,6 = $ ? $ $ ! ! 8 for ( n=0, i=100 ; n!=i ; n++, i.. ) { // whatever here... } $ n # 3 n 0! i 50 i ! 100! . 8 i n!=i 4 2 n # 3 i6 B ! n n i The C++ Language Tutorial @ K " break ! = 4 $ ! P68 // break loop example 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! #include <iostream> using namespace std; int main () { int n; for (n=10; n>0; n..) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; } continue ! % = $ ! 8 // continue loop example #include <iostream> using namespace std; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! int main () { for (int n=10; n>0; n..) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; } % goto $ + % ! ' 4:6 F ! & % = $ 5 ! goto8 The C++ Language Tutorial // goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! #include <iostream> using namespace std; int main () { int n=10; loop: cout << n << ", "; n..; if (n>0) goto loop; cout << "FIRE!\n"; return 0; } exit cstdlib $ exit " 8 void exit (int exitcode); B exitcode 0 ! $ $ $ $ $ " ) else if % if " 8 switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements } " $ 8 group of statements 1 % switch " $ # group of statements 2 = ! case default: # expression break ; constant2 " % constant1 ! ! $ 4 # ! switch 4 expression 6! 6 $ 1 ! constant1! break $ The C++ Language Tutorial B 8 6 . 7 $ switch (x) { if (x == 1) { case 1: cout << "x is 1"; cout << "x is 1"; } break; else if (x == 2) { case 2: cout << "x is 2"; cout << "x is 2"; } break; else { default: cout << "value of x unknown"; cout << "value of x unknown"; } } switch $ break & $ = & switch $ ! break ! break switch % $ break switch ! { } $ $ = $ 8 switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; } ( 4 $ case n: n $ 6 4case (1..3):6 " ! 3 if else if The C++ Language Tutorial & ( K ! ' $ 8 type name ( parameter1, parameter2, ...) { statements } 8 type name parameters 4 ! 68 A 4 . statements : $ $ 8 int x6 " { } 8 // function example #include <iostream> using namespace std; The result is 8 int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } " $ ! $ ; 8 ) main main addition 7 z int > ! 8 85 3! int a 0 ; int b main addition The C++ Language Tutorial ' addition b = main! 45 main 36 int a 4int r6! addition a b B a b $ 3 5 r=a+b! ! int r 8 8 return (r); ? addition! main6 ' addition B ! r 4return (r);6! 4 return 8 addition 8 ) ! z addition (5, 3)! 4addition (5,3)6 8 cout << "The result is " << z; ! $ ! 8 ! $ ! 486 The C++ Language Tutorial = a! b $ main z r ! $ addition ' ! addition! main ! J " J ' ! $ 8 ( ! ! The C++ Language Tutorial // function example #include <iostream> using namespace std; The The The The first result is 5 second result is 5 third result is 2 fourth result is 6 int subtraction (int a, int b) { int r; r=a.b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; } " subtraction ( ; ! $ " main subtraction $ = $ ! $ 4 68 z = subtraction (7,2); cout << "The first result is " << z; " 4 ! 56! 8 z = 5; cout << "The first result is " << z; ' cout << "The second result is " << subtraction (7,2); ! cout ) cout << "The second result is " << 5; 5 " subtraction (7,2) 8 cout << "The third result is " << subtraction (x,y); subtraction 8 The C++ Language Tutorial subtraction subtraction " ! 3 x y! 5 2 ) 8 z = 4 + subtraction (x,y); 8 z = subtraction (x,y) + 4; $ " 4;6 " $ 8 z = 4 + 2; z = 2 + 4; $ " $ 8 type name ( argument1, argument2 ...) statement 4 type! ! 6 B " % void " P ; // void function example #include <iostream> using namespace std; I'm a function! void printmessage () { cout << "I'm a function!"; } int main () { printmessage (); return 0; } void . = $ ! $ printmessage void printmessage (void) { cout << "I'm a function!"; } ' void " ! 8 The C++ Language Tutorial ; & $ = $ printmessage printmessage (); 8 printmessage; * 8 The C++ Language Tutorial & * K ( $ ! ! ! = $ ! addition 8 int x=5, y=3, z; z = addition ( x , y ); ; x x ! ! y! ! a x a b y b ! 3 5 ! 3 x ! B $ 5 y $ = 8 ! // passing parameters by reference #include <iostream> using namespace std; x=2, y=6, z=14 void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; } duplicate 4&6 ; ! 2 y The C++ Language Tutorial $ ! a! b a c y! . 4x! y c z6 ' x b z ! x! y z duplicate! main " 8 void duplicate (int& a, int& b, int& c) 8 void duplicate (int a, int b, int c) ! 4&6! ! ! ! x! y 7 = $ // more than one returning value #include <iostream> using namespace std; Previous=99, Next=101 void prevnext (int x, int& prev, int& next) { prev = x.1; next = x+1; } int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; } $ ; ! " ! ! = $ 8 5 $ z ! The C++ Language Tutorial // default values in functions #include <iostream> using namespace std; 6 5 int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; } ' divide " 8 divide (12) ! 4 ) divide 2 ! int b=2! % int b6 6 412/26 " 8 divide (20,4) ! ! 4! # b 4int b=26 5 420/46 1 b divide The C++ Language Tutorial )$ " = $ 8 // overloaded function #include <iostream> using namespace std; 10 2.5 int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; } " ! operate! int float $ " int float " operate J float! ! int! ; 8 ) operate ( ' inline ! ! ! 8 inline type name ( arguments ... ) { instructions ... } % + inline ! 3 The C++ Language Tutorial , ? # $ > " = $ ! ! 4 /6 8 n! = n * (n.1) * (n.2) * (n.3) ... * 1 ! /4 6 8 5! = 5 * 4 * 3 * 2 * 1 = 120 8 // factorial calculator #include <iostream> using namespace std; Please type a number: 9 9! = 362880 long factorial (long a) { if (a > 1) return (a * factorial (a.1)); else return (1); } int main () { long number; cout << "Please type a number: "; cin >> number; cout << number << "! = " << factorial (number); return 0; } ( ! factorial 0! 0 4 6 4long6 03/ K 0 /! ! " main $ ! main ! ! $ B % ! ! " 8 0 The C++ Language Tutorial type name ( argument_type1, argument_type2, ...); " ! $ 4 ! { }6 4;6 ! = protofunction $ int protofunction (int first, int second); int protofunction (int, int); ' ! // declaring functions prototypes #include <iostream> using namespace std; Type a Number Type a Number Type a Number Type a Number void odd (int a); void even (int a); int main () { int i; do { cout << "Type a number (0 to exit): "; cin >> i; odd (i); } while (i!=0); return 0; } number (0 is odd. number (0 is even. number (0 is even. number (0 is even. to exit): 9 to exit): 6 to exit): 1030 to exit): 0 void odd (int a) { if ((a%2)!=0) cout << "Number is odd.\n"; else even (a); } void even (int a) { if ((a%2)==0) cout << "Number is even.\n"; else odd (a); } $ $ " ! $ $ , ! $ odd even8 void odd (int a); void even (int a); ! $ ! 8 ' ! odd even even ! 8 int odd " main! ' The C++ Language Tutorial ! 4 ! 6! : ! even odd even odd 4 6 The C++ Language Tutorial Compound data types * ' $ ! $ # ! ! ! int = int ! " $ $ ! # ! int 8 billy ! 0 < int $ 4 ! 0! ' 8 type name [elements]; 4 type # int! float []6! 6! name ! elements 4 8 billy int billy [5]; ) 88 elements ! [] ! $ & ? " ! $ ! ; 4 ? ! $ 6! ! ! ! " ! ! ! ? ? ! ! { } = int billy [5] = { 16, 2, 77, 40, 12071 }; 8 $ 8 The C++ Language Tutorial # [ ] = { } $ ! $ billy ! { } ; ? ! [ ] " ! # ? { }8 int billy [] = { 16, 2, 77, 40, 12071 }; ' ! ! billy * ? $ " ! ! 8 name[index] = $ billy int! 8 = $ ! 75 8 billy! billy[2] = 75; ! $ ! billy 8 a! a = billy[2]; ! $ ( billy[1]! billy[2] int billy billy[2]! billy[2] B $ billy ! Q R! " billy[0]! ! $ ! billy[4] ? $ ! & & ' [ ] 8 ? - ] J [ The C++ Language Tutorial int billy[5]; billy[2] = 75; " // declaration of a new array // access to an element of the array. ! ) ! 8 billy[0] = a; billy[a] = 75; b = billy [a+2]; billy[billy[a]] = billy[2] + 5; // arrays example #include <iostream> using namespace std; 12206 int billy [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0; } A , 9 9 = $ ! ! jimmy int 8 int jimmy [3][5]; ! $ 8 ! ? jimmy[1][3] * $ The C++ Language Tutorial 4 ? , $ 6 4 B 8 ! 6 / = char century [100][365][24][60][60]; ! char ) / , % ! % int jimmy [3][5]; int jimmy [15]; 8 // is equivalent to // (3 * 5 = 15) ; $ ! $ 8 #define WIDTH 5 #define HEIGHT 3 . #define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT][WIDTH]; int n,m; int jimmy [HEIGHT * WIDTH]; int n,m; int main () int main () { { for (n=0;n<HEIGHT;n++) for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) for (m=0;m<WIDTH;m++) { { jimmy[n*WIDTH+m]=(n+1)*(m+1); jimmy[n][m]=(n+1)*(m+1); } } return 0; return 0; } } ( ! % 8 2 The C++ Language Tutorial ; 9 9 4#define6 = $ 8 #define HEIGHT 3 8 #define HEIGHT 4 * ' " ! " " ! [] = $ ! 8 void procedure (int arg[]) 9 int9 arg " 8 int myarray [40]; 8 procedure (myarray); : $ 8 // arrays as parameters #include <iostream> using namespace std; 5 10 15 2 4 6 8 10 void printarray (int arg[], int length) { for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n"; } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); return 0; } ' ! 4int arg[]6 int! = 5 ! The C++ Language Tutorial for " 8 base_type[][depth][depth] $ ! 8 void procedure (int myarray[][3][4]) ( ' [] ! ! # " 7 1 The C++ Language Tutorial 7 ' ! ) < : ! ! # ! char = $ ! 8 char jenny [20]; 3 ! char " ! ! # = $ ! jenny "Merry christmas"! # # 3 B # # # !? 8 ! ! '\0' 6 3 "Merry Christmas" char! # jenny! 8 ( 4'\0'6 # char ! . 7 B = $ ? # 8 char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; " * "Hello" char B " "Hello" 3 ! 4 8 char ? '\0' ? $ $ 8 ! $ # 496 = $ 8 "the result is: " *3 ! % "Hello" The C++ Language Tutorial - # 4"6 & 4'\0'6 # ? char ) & myword # 8 char myword [] = { 'H', 'e', 'l', 'l', 'o', '\0' }; char myword [] = "Hello"; " ? myword * char8 4'\0'6 "Hello" ! # # ! 4"6 7 ? ! & " ! ' mystext ! $ char[] 8 mystext = "Hello"; mystext[] = "Hello"; ! 8 mystext = { 'H', 'e', 'l', 'l', 'o', '\0' }; ! B ( . & 7 # ! " = $ ! cin ! 4char[]6 & cout # $ cin *0 # cout = ! $ 8 The C++ Language Tutorial // null.terminated sequences of characters #include <iostream> using namespace std; Please, enter your first name: John Hello, John! int main () { char question[] = "Please, enter your first name: "; char greeting[] = "Hello, "; char yourname [80]; cout << question; cin >> yourname; cout << greeting << yourname << "!"; return 0; } ' = ! ! 4question ? ; ! ? greeting6 yourname # char " ? ? ! 8 ? $ ? char 53 string 8 string mystring; char myntcs[]="some text"; mystring = myntcs; * % % The C++ Language Tutorial < ; ! ! 4 6 ? & ! ! ! ! # = $ 0222! $ 022 # ! 022* 22* $ 22* &3( ' 4 ! 6 ; $ &= : ! ! 4&6! ! ted = &andy; 9 ted 4&6 4 ! 9 = $ 8 andy! andy ! 6 = 417766 andy 1776 % ! ! 8 andy = 25; fred = andy; ted = &andy; $ = ! ! andy 4 8 022*6 * The C++ Language Tutorial andy 4 fred 6 ! = ! ted 4 andy ! ! 17766 4&6! andy 4 6 4 $ ted 6 7 = ! &"( ; % 9 7 9 K ! . 4E6! 9 9 ! $ ! 8 beth = *ted; 4 8 9beth # 022* ted96 beth + $ 25! ted 1776! 6 1776! 4" $ beth = ted; beth = *ted; $ 68 // beth equal to ted ( 1776 ) // beth equal to value pointed by ted ( 25 ) ( 8 S 9 E 9 9 * 9 *ted 4 25 ( ted 1776! * The C++ Language Tutorial ! 4 6 ' & A * 8 andy = 25; ted = &andy; > ! $ 8 andy == 25 &andy == 1776 ted == 1776 *ted == 25 $ # andy 4&6! $ 1776 ted % ! ) ! andy=25 andy! $ ted=&andy 9 4*6 9! ted ! ! 25 ted $ 8 *ted == andy $ - ! " int char float 8 type * name; type / = $ 8 int * number; char * character; float * greatnumber; A ! 4 6 ( 8 char ! float ? " 4 ! int! $ ! 8 int*! char* ? ? 4*6 6! ! 4*6 * float* ! The C++ Language Tutorial ( 8 // my first pointer #include <iostream> using namespace std; firstvalue is 10 secondvalue is 20 int main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; } ( firstvalue 8 mypointer = ! mypointer 03 firstvalue! secondvalue! 4&6 ' firstvalue mypointer! firstvalue " " ! mypointer secondvalue : $ 8 // more pointers #include <iostream> using namespace std; firstvalue is 10 secondvalue is 20 int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; p2 = &secondvalue; *p1 = 10; *p2 = *p1; p1 p1 = p2; *p1 = 20; // // // // p1 = address of firstvalue p2 = address of secondvalue value pointed by p1 = 10 value pointed by p2 = value pointed by // p1 = p2 (value of pointer is copied) // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; } " 4*6 8 9 4&6 9 9 9 ( $ p1 $ ! 4*6 8; p2! 4*6 $ ! ! 4 6 ** The C++ Language Tutorial ' 8 int * p1, * p2; $ ! int* 4 B 4E6 int6 ! int 4 " int*6 8 int * p1, p2; p1 ! int* int 4 p2 B 6 ! < " ! ! # # = $ ! ! 8 int numbers [20]; int * p; 8 p = numbers; ' !p # numbers ! p ! int ! 3 numbers p! ! ! numbers 8 numbers = p; B numbers - ! ! ! $ $ 8 *2 The C++ Language Tutorial // more pointers #include <iostream> using namespace std; 10, 20, 30, 40, 50, int main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; return 0; } " 4[]6 ; $ ! % = a[5] = 0; *(a+5) = 0; $ * [] ! 8 // a [offset of 5] = 0 // pointed by (a+5) = 0 $ # < a a ! ; $ 8 int number; int *tommy = &number; # 8 int number; int *tommy; tommy = &number; ; 4tommy6! ? 4*tommy6 + ! 4*6 E6 > ! 4 ! 8 ! 8 int number; int *tommy; *tommy = &number; ! ' ! ? 8 char * terry = "hello"; *5 The C++ Language Tutorial " ! "hello" "hello" 8 terry " 023 ! " 023 ! terry 023 "hello"! # terry % 4 6 = $ 'h' $ ! 8 *(terry+4) terry[4] B $ 'o' 4 6 < ! ! B ? ; ! = $ long ! . ! char ) 8 char *mychar; short *myshort; long *mylong; 1000! 2000 ) 3000 8 mychar++; myshort++; mylong++; mychar! 2002! $ mylong ! ! 1001 B 3004! ? *1 ! myshort 0 ! short The C++ Language Tutorial " $ 8 mychar = mychar + 1; myshort = myshort + 1; mylong = mylong + 1; B 4++6 4..6 4*6! $4 6 ! $ $ 8 *p++ B ++ $ $ *! 4 # ! *(p++) 6! $ $ 4 6 ( 8 (*p)++ : ! $ " p4 p 6 4 6 8 *p++ = *q++; B ++ *! $ " p $! # q *p ! 4++6 *q p 8 *p = *q; ++p; ++q; < !" $ () 23 q ' The C++ Language Tutorial < ! 6 " char a; char * b; char ** c; a = 'z'; b = &a; c = &b; ! 4*6 ! ! ! 4 8 7230! 8092 10502! 8 J $ ! c! 8 c char** 8092 *c char* 7230 **c char 'z' $ " void ! void ! 4 6 ! $ B 8 4 6! 8 20 ! The C++ Language Tutorial // increaser #include <iostream> using namespace std; y, 1603 void increase (void* data, int psize) { if ( psize == sizeof(char) ) { char* pchar; pchar=(char*)data; ++(*pchar); } else if (psize == sizeof(int) ) { int* pint; pint=(int*)data; ++(*pint); } } int main () { char a = 'x'; int b = 1602; increase (&a,sizeof(a)); increase (&b,sizeof(b)); cout << a << ", " << b << endl; return 0; } ? ! sizeof(char) sizeof ! $ 1! = char ' & int * p; p = 0; // p has a null pointer value - ' 9 9! < ! " $ () 4*6 8 2 ? & The C++ Language Tutorial // pointer to functions #include <iostream> using namespace std; 8 int addition (int a, int b) { return (a+b); } int subtraction (int a, int b) { return (a.b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return (g); } int main () { int m,n; int (*minus)(int,int) = subtraction; m = operation (7, 5, addition); n = operation (20, m, minus); cout <<n; return 0; } " $ ! minus subtraction! int " 8 int (* minus)(int,int) = subtraction; 2 The C++ Language Tutorial A K ! ! ? ! $ P= ! new ) ! ! B $ ! delete CD " # & new new # # & [] " " 8 pointer = new type pointer = new type [number_of_elements] $ type 4 6 $ = type! number_of_elements 8 int * bobby; bobby = new int [5]; " ! int # ! ! bobby ! bobby int $ B # bobby[1] bobby[0] $ *bobby $ *(bobby+1) + ! % ! ? ? ! $ ! $ 4 6 ? # : ! $ ! # 8 $ A$ $ K $ bad_alloc B $ ! 2 $ ! The C++ Language Tutorial $ ! bobby = new int [5]; 8 // if it fails an exception is thrown ! nothrow! bad_alloc $ ! ! new $ % nothrow! <new>! new8 bobby = new (nothrow) int [5]; " ! ! bobby 8 int * bobby; bobby = new (nothrow) int [5]; if (bobby == 0) { // error assigning memory. Take measures. }; # nothrow $ ! % ! ! " $ ' $ $ $ ) CD ) ! # 8 delete! delete pointer; delete [] pointer; $ ! new! 4 ! delete 6 2 The C++ Language Tutorial // rememb.o.matic #include <iostream> #include <new> using namespace std; int main () { int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new (nothrow) int[i]; if (p == 0) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n++) { cout << "Enter number: "; cin >> p[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << p[n] << ", "; delete[] p; } return 0; } ( How many numbers would you like to type? 5 Enter number : 75 Enter number : 436 Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32, 4i6! new 8 p= new (nothrow) int[i]; B = 0 " 9: $ 9# $ ! " ! 4Error: memory could not be allocated6 > $ ! $ ! . " ! nothrow ! $ $ ! $ * new ! $ ! delete ! . $ B ! 4 <cstdlib> ! ! 6 ! 2* The C++ Language Tutorial ; # B ! # ! ' ! ! - $8 T T T T H % G T T T 0 T 0J J J J ! object_name structure_name ; % ! { } 8 ! structure_name = $ 8 struct product { int weight; float price; } ; product apple; product banana, melon; ; 8 weight 4product6 product ; 8 apple! banana % melon ! product % apple! banana price! 4 int! char ! 6 short melon > struct object_name % % apple! banana melon ! ! = $ ! 8 struct product { int weight; float price; } apple, banana, melon; " ! ; 4product6 % 22 4 ! % apple! banana 4 melon6 6 The C++ Language Tutorial % 4apple! banana 4.6 = $ 8 melon6 % ! apple.weight apple.price banana.weight banana.price melon.weight melon.price A melon.weight < . int! apple.price! banana.price 8 apple.weight! banana.weight melon.price float $ 8 // example about structures #include <iostream> #include <string> #include <sstream> using namespace std; Enter title: Alien Enter year: 1979 My favorite movie is: 2001 A Space Odyssey (1968) And yours is: Alien (1979) struct movies_t { string title; int year; } mine, yours; void printmovie (movies_t movie); int main () { string mystr; mine.title = "2001 A Space Odyssey"; mine.year = 1968; cout << "Enter title: "; getline (cin,yours.title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> yours.year; cout << "My favorite movie is:\n "; printmovie (mine); cout << "And yours is:\n "; printmovie (yours); return 0; } void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")\n"; } $ yours.year % int! mine % mine.title yours printmovie = movies_t! 25 $ string $ ! ! The C++ Language Tutorial - ! 8 // array of structures #include <iostream> #include <string> #include <sstream> using namespace std; Enter Enter Enter Enter Enter Enter title: Blade Runner year: 1982 title: Matrix year: 1999 title: Taxi Driver year: 1976 #define N_MOVIES 3 You have entered these movies: Blade Runner (1982) Matrix (1999) Taxi Driver (1976) struct movies_t { string title; int year; } films [N_MOVIES]; void printmovie (movies_t movie); int main () { string mystr; int n; for (n=0; n<N_MOVIES; n++) { cout << "Enter title: "; getline (cin,films[n].title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> films[n].year; } cout << "\nYou have entered these movies:\n"; for (n=0; n<N_MOVIES; n++) printmovie (films[n]); return 0; } void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")\n"; } < < ! struct movies_t { string title; int year; }; 8 movies_t amovie; movies_t * pmovie; : amovie movies_t ) ! % movies_t! 8 % pmovie pmovie = &amovie; % pmovie 21 amovie 4 6 The C++ Language Tutorial ; $ ! 8 4.>68 // pointers to structures #include <iostream> #include <string> #include <sstream> using namespace std; Enter title: Invasion of the body snatchers Enter year: 1978 You have entered: Invasion of the body snatchers (1978) struct movies_t { string title; int year; }; int main () { string mystr; movies_t amovie; movies_t * pmovie; pmovie = &amovie; cout << "Enter title: "; getline (cin, pmovie.>title); cout << "Enter year: "; getline (cin, mystr); (stringstream) mystr >> pmovie.>year; cout << "\nYou have entered:\n"; cout << pmovie.>title; cout << " (" << pmovie.>year << ")\n"; return 0; } 8 $ 4.>6 % " % $ 8 pmovie.>title ; # 8 (*pmovie).title B $ pmovie.>title (*pmovie).title pmovie " title 8 *pmovie.title # 8 *(pmovie.title) ' pmovie 4 title 6 ? 8 53 % The C++ Language Tutorial 86 E , , @ &N E $ 87 % % % $ 4E 6 E4 6 ) struct movies_t { string title; int year; }; struct friends_t { string name; string email; movies_t favorite_movie; } charlie, maria; friends_t * pfriends = &charlie; ' $ 8 charlie.name maria.favorite_movie.title charlie.favorite_movie.year pfriends.>favorite_movie.year 4 ! ! $ 6 50 The C++ Language Tutorial ) & ( $ ; 8 typedef! typedef existing_type new_type_name ; existing_type = $ typedef typedef typedef typedef " char[50] new_type_name 8 char C; unsigned int WORD; char * pChar; char field [50]; 8 C! WORD! pChar field ! char! unsigned int! char* 8 C mychar, anotherchar, *ptc1; WORD myword; pChar ptc2; field name; " WORD typedef myword $ unsigned int! # typedef " ! B K ! " 8 union union_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names; ' " union = $ 8 5 ? The C++ Language Tutorial union mytypes_t { char c; int i; float f; } mytypes; 8 mytypes.c mytypes.i mytypes.f ) ! ; = $ 8 union mix_t { long l; struct { short hi; short lo; } s; char c[4]; } mix; ! short ! char 6! " 8 mix.l! mix.s long& $ ! = mix.c ! 4 7 8 $ * " " ! = 8 5 $ ! The C++ Language Tutorial struct { char title[50]; char author[50]; union { float dollars; int yens; } price; } book; 4price6 yens struct { char title[50]; char author[50]; union { float dollars; int yens; }; } book; dollars % = % ! 8 book.price.dollars book.price.yens % ! 8 book.dollars book.yens " ! dollars yens + ! price 8 & ( A " 8 enum enumeration_name { value1, value2, value3, . . } object_names; = $ ! 8 color enum colors_t {black, blue, green, cyan, red, purple, yellow, white}; ( ! $ = color_t $ colors_t $ ! 8 colors_t mycolor; mycolor = blue; if (mycolor == green) mycolor = red; A ! " 0 black ! # 0 # 0! blue # ! # colors_t 1! green 5 2! ! The C++ Language Tutorial ; $ " ! = $ 8 enum months_t { january=1, february, march, april, may, june, july, august, september, october, november, december} y2k; " ! y2k january december january # 16 0 months_t # 1 5 12 4 0 11! The C++ Language Tutorial Object Oriented Programming & ( ' $ 8 ' ! " ! ! % 8 class! class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names; ; ! object_names ! class_name ' % ! ! $ ' ! 8 private! public # 8 protected private ! protected = B $ ! public % ! ! class = 8 class CRectangle { int x, y; public: void set_values (int,int); int area (void); } rect; - 4 ! 6 % CRectangle 8 int 4 4 ! x 6 6 y6 8 set_values() rect 4 area()! ! ( % 4 ! 6! % 8 5* 8" CRectangle " $ ! CRectangle int a The C++ Language Tutorial int a; 4 int ' = % 4.6 $ 6 4 a CRectangle rect % 6 rect! !% % ' 8 rect.set_values (3,4); myarea = rect.area(); x : $ > y! 8 // classes example #include <iostream> using namespace std; area: 12 class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } 4::! 6 set_values() " + $ CRectangle ! ! " area() set_values() ! CRectangle 4::6 4::6 ! ! set_values() CRectangle! x $ = y! $ ! ! ! , x 4 4 y & ! 6 B 52 6 ! . The C++ Language Tutorial ! % 8 ! 4 ! set_values() $ 7 ! % $ $ % 6 ! $ ! ! CRectangle! $ % % % = rectb rect8 // example: one class, two objects #include <iostream> using namespace std; rect area: 12 rectb area: 30 class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } " ! % ( % 4 8 rect % rectb A rect.area() > set_value() area() 6 CRectangle! x % rectb.area() ! ! y! . 8- % ; ! % ( rect.area rectb.area rect rectb % % ? $ $ $ " $ ! set_values()P 7 x ! y constructor! % ! J ; = area() void 8 CRectangle 55 The C++ Language Tutorial // example: class constructor #include <iostream> using namespace std; rect area: 12 rectb area: 30 class CRectangle { int width, height; public: CRectangle (int,int); int area () {return (width*height);} }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } ' ! set_values()! x y $ B 8 ( ? % 8 CRectangle rect (3,4); CRectangle rectb (5,6); $ $ % + 4 J $ 6 6 void 4 " $ % ! ! % % ! 4~6 % % 51 The C++ Language Tutorial // example on constructors and destructors #include <iostream> using namespace std; rect area: 12 rectb area: 30 class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () {return (*width * *height);} }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } )$ < ! > " % % ! $ 8 13 ! The C++ Language Tutorial // overloading class constructors #include <iostream> using namespace std; rect area: 12 rectb area: 25 class CRectangle { int width, height; public: CRectangle (); CRectangle (int,int); int area (void) {return (width*height);} }; CRectangle::CRectangle () { width = 5; height = 5; } CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb; cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } " ! rectb ! ! ? width ? height ( 6! % ()8 4 CRectangle rectb; // right CRectangle rectb(); // wrong! " ! ! 8 class CExample { public: int a,b,c; void multiply (int n, int m) { a=n; b=m; c=a*b; }; }; ! CExample 8 CExample ex; B ! ) % 8 10 % The C++ Language Tutorial class CExample { public: int a,b,c; CExample (int n, int m) { a=n; b=m; }; void multiply () { c=a*b; }; }; : % 8 CExample ex (2,3); B ! CExample ex; ; ! $ ! B " ! ! % % = CExample! 8 CExample::CExample (const CExample& rv) { a=rv.a; b=rv.b; c=rv.c; } ! % CExample ex (2,3); CExample ex2 (ex); 8 // copy constructor (data copied from ex) < " ; ! CRectangle * prect; % ! = $ 8 CRectangle ' ! 4.>6 % : $ 8 1 The C++ Language Tutorial // pointer to classes example #include <iostream> using namespace std; a area: 2 *b area: 12 *c area: 2 d[0] area: 30 d[1] area: 56 class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return (width * height);} }; void CRectangle::set_values (int a, int b) { width = a; height = b; } int main () { CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b.>set_values (3,4); d.>set_values (5,6); d[1].set_values (7,8); cout << "a area: " << a.area() << endl; cout << "*b area: " << b.>area() << endl; cout << "*c area: " << c.>area() << endl; cout << "d[0] area: " << d[0].area() << endl; cout << "d[1] area: " << d[1].area() << endl; delete[] d; delete b; return 0; } ( $ 4*! &! .! .>! [ ]6 $ 6 E$ S$ $ $&N 4E$6 $Q3R $Q0R $Q R 8 $ $ % % % % $ $4 # 6 $ % 4 $ 06 % $ $ B $ ! $ C class! struct 4struct 4 union class6 ! struct 6 struct ! class # 1 = " The C++ Language Tutorial struct ! 1 class! The C++ Language Tutorial & ( )$ = $ 8 int a, b, c; a = b + c; ! ( ! 8 struct { string product; float price; } a, b, c; a = b + c; " ! ! : ! ! : + . <<= >>= ~ &= delete * / == != ^= |= new[] )$ = < <= >= && || delete[] > ++ %= += .. [] .= % () 8 *= & , /= ^ .>* << ! .> >> | new ! 8 operator type operator sign (parameters) { /*...*/ } : $ y 4+6 ; 8 a(3,1) x y " 1 b(1,2) x (3+1,1+2) = (4,3) The C++ Language Tutorial // vectors: overloading operators example #include <iostream> using namespace std; 4,3 class CVector { public: int x,y; CVector () {}; CVector (int,int); CVector operator + (CVector); }; CVector::CVector (int a, int b) { x = a; y = b; } CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); } int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; } " B CVector 4 6 CVector 6 - 4 8 CVector (int, int); CVector operator+ (CVector); operator+ ! // function name CVector (constructor) // function returns a CVector 4+6 CVector ! $ 8 c = a + b; c = a.operator+ (b); B $ # ( 4 6 8 CVector () { }; ! $ 8 CVector (int, int); ' $ ! ! ! % ! 1* 8 The C++ Language Tutorial CVector c; main() ' !" ! $ ! ? " x ! y 8 CVector () { x=0; y=0; }; " $ ' ! 4=6 % 6 4 8 CVector d (2,3); CVector e; e = d; // copy assignment operator ! ! $ ! ? ! = ' $ ! operator + ? operator== ! operator+ % ! : 4 U 86 U U U U 4 ! &N$ 6 ; 68 ) A &ES/D && '88 && '88 & E C L V S W O N MM /M OM NM OO NN SS WW ! '88 M M &M EM CM LM VM SM WM OOM NNM QR '88 46 '88 &N '88 % a % A! b B c + ? U46 U4 6 U 4B6 U 4B6 46 4B! &N46 % U4'6 U4'! 6 U4'!B6 & 6& & C 8 " ! " 4 $ 6 F this % $ % 12 " The C++ Language Tutorial % // this #include <iostream> using namespace std; = $ ! yes, &a is b class CDummy { public: int isitme (CDummy& param); }; int CDummy::isitme (CDummy& param) { if (&param == this) return true; else return false; } int main () { CDummy a; CDummy* b = &a; if ( b.>isitme(a) ) cout << "yes, &a is b"; return 0; } " # % operator= % 6 = 8 . $ 4 operator= CVector& CVector::operator= (const CVector& param) { x=param.x; y=param.y; return *this; } " % operator= ' ! ) 9 9! % = $ # % ! % ! $ 15 8 The C++ Language Tutorial // static members in classes #include <iostream> using namespace std; 7 6 class CDummy { public: static int n; CDummy () { n++; }; ~CDummy () { n..; }; }; int CDummy::n=0; int main () { CDummy a; CDummy b[5]; CDummy * c = new CDummy; cout << a.n << endl; delete c; cout << CDummy::n << endl; return 0; } " ! % ! 4 ? 6 " ! 4 & ? ! $ = 6 ! 8 int CDummy::n=0; B # % % ! 4 68 cout << a.n; cout << CDummy::n; $ CDummy 8 n % !" X ! 8 % ! this! & ! % % 11 The C++ Language Tutorial " ! : ! = " $ ! ! friend8 ! // friend functions #include <iostream> using namespace std; $ 24 class CRectangle { int width, height; public: void set_values (int, int); int area () {return (width * height);} friend CRectangle duplicate (CRectangle); }; void CRectangle::set_values (int a, int b) { width = a; height = b; } CRectangle duplicate (CRectangle rectparam) { CRectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres); } int main () { CRectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << rectb.area(); return 0; } duplicate width CRectangle = % duplicate() ./" height CRectangle " ! $ ( duplicate CRectangle! main() ! % duplicate() F & ! ) CRectangle 033 $ ! ! The C++ Language Tutorial X ! // friend class #include <iostream> using namespace std; ! 16 class CSquare; class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle; }; void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0; } " $ ! CRectangle CSquare CSquare! CRectangle CSquare::side! # + 8 )# CRectangle CSquare CSquare convert()6 CSquare 4 ! CRectangle $ " CSquare CSquare! CSquare CRectangle CSquare CRectangle ' $ ! CRectangle ! CRectangle ! 8 $ ' " ! 9 . 9 030 ! = $ ! The C++ Language Tutorial CRectangle! ! CTriangle 8 CPolygon 8 CRectangle CTriangle " CPolygon height ' CRectangle A A 8 width ! CTriangle B! B " ! 4:6 8 class derived_class_name: public base_class_name { /*...*/ }; ; derived_class_name public private base_class_name protected 03 The C++ Language Tutorial // derived classes #include <iostream> using namespace std; 20 10 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; } % width! height CRectangle set_values() CTriangle private " protected ; ! ! ) CTriangle width height CPolygon! ; ; " CRectangle private protected ? 8 * $ 9 $ 9 ! ! 8 CPolygon CRectangle CTriangle CPolygon8 03 main()! The C++ Language Tutorial CPolygon::width CRectangle::width // protected access // protected access CPolygon::set_values() CRectangle::set_values() // public access // public access public 8 class CRectangle: public CPolygon { ... } 4:6 CPolygon6 ) public 4 " $ public ! protected! ; = $ ! 8 private! daughter 8 mother class daughter: protected mother; protected ! daughter mother mother " $ daughter daughter mother $ $ class ! struct E " ! $ 8 M46 ' 4 ! ! 6 % " % ! 8 derived_constructor_name (parameters) : base_constructor_name (parameters) {...} = $ 8 03 ! The C++ Language Tutorial // constructors and derived classes #include <iostream> using namespace std; mother: no parameters daughter: int parameter mother: int parameter son: int parameter class mother { public: mother () { cout << "mother: no parameters\n"; } mother (int a) { cout << "mother: int parameter\n"; } }; class daughter : public mother { public: daughter (int a) { cout << "daughter: int parameter\n\n"; } }; class son : public mother { public: son (int a) : mother (a) { cout << "son: int parameter\n\n"; } }; int main () { daughter cynthia (0); son daniel(0); return 0; } ( daughter % daughter mother. % son daughter (int a) son (int a) : mother (a) // nothing specified: call default // constructor specified: call this A " = 4COutput6 CPolygon 8 class CRectangle: public CPolygon, public COutput; class CTriangle: public CPolygon, public COutput; $ 8 03 CRectangle $ ! CTriangle son8 The C++ Language Tutorial // multiple inheritance #include <iostream> using namespace std; 20 10 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class COutput { public: void output (int i); }; void COutput::output (int i) { cout << i << endl; } class CRectangle: public CPolygon, public COutput { public: int area () { return (width * height); } }; class CTriangle: public CPolygon, public COutput { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0; } 03* The C++ Language Tutorial < B ! " ! 8 86 88 4 6 GHJ &N J= 8 ) < & 7 % ! , ; 8 // pointers to base class #include <iostream> using namespace std; 20 10 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1.>set_values (4,5); ppoly2.>set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; } " % main! rect CPolygon 4ppoly1 % ! trgl ppoly26 CPolygon! *ppoly1 *ppoly2 rect CPolygon* 032 trgl *ppoly1 *ppoly2 CRectangle The C++ Language Tutorial CPolygon = % rect CTriangle " area() *ppoly1 trgl area() CPolygon! area! 8 CPolygon! ! *ppoly2 CRectangle ' CTriangle " ! // virtual members #include <iostream> using namespace std; virtual8 20 10 0 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area () { return (0); } }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon poly; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; CPolygon * ppoly3 = &poly; ppoly1.>set_values (4,5); ppoly2.>set_values (4,5); ppoly3.>set_values (4,5); cout << ppoly1.>area() << endl; cout << ppoly2.>area() << endl; cout << ppoly3.>area() << endl; return 0; } ( set_values() 4CPolygon! CRectangle area() 8 width! height! CTriangle6 area() + CPolygon! CTriangle::area() virtual 0 CPolygon::area()! CPolygon* area() % 6! CPolygon::area() 035 area() 20! 10 0 4CRectangle::area()! The C++ Language Tutorial ! virtual ! % ! $ ' ( area() ! % ! CPolygon 3 * ' $ CPolygon $ CPolygon 4 % area() area() % poly6! =0 4 # ' 7 ? 6 8 // abstract class CPolygon class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area () =0; }; ( =0 virtual int area () ! 4 B % % 6 ; 8 CPolygon poly; % ( ! ! % 8 CPolygon * ppoly1; CPolygon * ppoly2; . CPolygon : : ! % $ 8 031 The C++ Language Tutorial // abstract base class #include <iostream> using namespace std; 20 10 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1.>set_values (4,5); ppoly2.>set_values (4,5); cout << ppoly1.>area() << endl; cout << ppoly2.>area() << endl; return 0; } " % 4CPolygon*6 CPolygon CPolygon # = $ ! area() 8 003 The C++ Language Tutorial // pure virtual members can be called // from the abstract base class #include <iostream> using namespace std; 20 10 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout << this.>area() << endl; } }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1.>set_values (4,5); ppoly2.>set_values (4,5); ppoly1.>printarea(); ppoly2.>printarea(); return 0; } @ % % % < . $ & ! ! % ! % 000 8 The C++ Language Tutorial // dynamic allocation and polymorphism #include <iostream> using namespace std; 20 10 class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout << this.>area() << endl; } }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CPolygon * ppoly1 = new CRectangle; CPolygon * ppoly2 = new CTriangle; ppoly1.>set_values (4,5); ppoly2.>set_values (4,5); ppoly1.>printarea(); ppoly2.>printarea(); delete ppoly1; delete ppoly2; return 0; } ( ppoly 8 CPolygon * ppoly1 = new CRectangle; CPolygon * ppoly2 = new CTriangle; CPolygon % 00 The C++ Language Tutorial Advanced concepts = " ' 8% ! 8 template <class identifier> function_declaration; template <typename identifier> function_declaration; typename " class ! = $ $ $ $ ! % 8 template <class myType> myType GetMax (myType a, myType b) { return (a>b?a:b); } : ' myType ! GetMax ! & 8 function_name <type> (parameters); = $ ! GetMax int 8 int x,y; GetMax <int> (x,y); ; ! 4int myType 6 : $ 8 00 The C++ Language Tutorial // function template #include <iostream> using namespace std; 6 10 template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax<int>(i,j); n=GetMax<long>(l,m); cout << k << endl; cout << n << endl; return 0; } " ! T myType B " $ GetMax() int long ' ! T % GetMax() 8 T result; ! result % " a T b GetMax $ <int> <long>6 ) int i,j; GetMax (i,j); ) i int j 4 8 int! $ 8 00 The C++ Language Tutorial // function template II #include <iostream> using namespace std; 6 10 template <class T> T GetMax (T a, T b) { return (a>b?a:b); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout << k << endl; cout << n << endl; return 0; } ( ! & GetMax() $ <> B 4class T6 ! ! T % 8 int i; long l; k = GetMax (i,l); ! $ GetMax ! % ; ! = $ 8 template <class T, class U> T GetMin (T a, U b) { return (a<b?a:b); } " ! GetMin() 4T6 = $ 8 int i,j; long l; i = GetMin<int,long> (j,l); 8 i = GetMin (j,l); j l ! 00 ! % GetMin() The C++ Language Tutorial ; ! = $ 8 template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } }; % = % $ 00 int mypair<int> myobject (115, 36); % 8 mypair<double> myfloats (3.0, 2.18); " ! template <...> // class templates #include <iostream> using namespace std; $8 100 template <class T> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); }; template <class T> T mypair<T>::getmax () { T retval; retval = a>b? a : b; return retval; } int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; } ( $ $8 00* ! * 8 The C++ Language Tutorial template <class T> T mypair<T>::getmax () T. P 8 T. ' T # 8" T4 6 . ! " ! = $ ? ! . mycontainer % B increase! char uppercase! ? // template specialization #include <iostream> using namespace std; 8 J // class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) {element=arg;} T increase () {return ++element;} }; // class template specialization: template <> class mycontainer <char> { char element; public: mycontainer (char arg) {element=arg;} char uppercase () { if ((element>='a')&&(element<='z')) element+='A'.'a'; return element; } }; int main () { mycontainer<int> myint (7); mycontainer<char> mychar ('j'); cout << myint.increase() << endl; cout << mychar.uppercase() << endl; return 0; } $ ? 8 template <> class mycontainer <char> { ... }; = ! $ template<> ? 002 8 The C++ Language Tutorial B $! ? <char> ? 4char6 ( ? ? 8 template <class T> class mycontainer { ... }; template <> class mycontainer <char> { ... }; ! ; # ? ? ! ! ! 9 $ 9 ? . B class ! ' typename ! # ! $ 8 // sequence template #include <iostream> using namespace std; 100 3.1416 template <class T, int N> class mysequence { T memblock [N]; public: void setmember (int x, T value); T getmember (int x); }; template <class T, int N> void mysequence<T,N>::setmember (int x, T value) { memblock[x]=value; } template <class T, int N> T mysequence<T,N>::getmember (int x) { return memblock[x]; } int main () { mysequence <int,5> myints; mysequence <double,5> myfloats; myints.setmember (0,100); myfloats.setmember (3,3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0; } " = 8 template <class T=char, int N=10> class mysequence {..}; ; % 8 mysequence<> myseq; ; # 8 005 $ ! ! The C++ Language Tutorial mysequence<char,10> myseq; . = G ! ! # ; ' ! # ! % " ! $ 9 B 4 9 $ ! # ! 4 6 ! & % 8 6 ! ) # ! % 001 The C++ Language Tutorial ( ! 9 & % 9! 8 namespace identifier { entities } ; identifier ! entities = $ % 8 namespace myNamespace { int a, b; } " ! $ a myNamespace " :: = b myNamespace myNamespace ! 8 myNamespace::a myNamespace::b % ! // namespaces #include <iostream> using namespace std; = $ 8 5 3.1416 namespace first { int var = 5; } namespace second { double var = 3.1416; } int main () { cout << first::var << endl; cout << second::var << endl; return 0; } " ! 8 var second ( 0 3 first The C++ Language Tutorial = using $ 8 // using #include <iostream> using namespace std; 5 2.7183 10 3.1416 namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; } ( !x4 using # 6 first::x first::y ; y second::x second::y! $ # 8 // using #include <iostream> using namespace std; 5 10 3.1416 2.7183 namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; } " # ! using namespace first! namespace first 0 0 x y The C++ Language Tutorial using using namespace = ! $ ! % 8 // using namespace example #include <iostream> using namespace std; 5 3.1416 namespace first { int x = 5; } namespace second { double x = 3.1416; } int main () { { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0; } ; $ 8 namespace new_name = current_name; ' std using namespace std; iostream 0 The C++ Language Tutorial 86 A$ $ 4 $ 6 $ ; $ ! $ " $ $ ! ' $ A$ 8 catch! // exceptions #include <iostream> using namespace std; An exception occurred. Exception Nr. 20 int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. " cout << "Exception Nr. " << e << endl; } return 0; } $ $ " try $ 8 throw 20; ' $ 4 206! $ $ try ' catch ! ! $ ! ! ; 4 $ $ 6! $ " 4...6 throw $ $ catch! $ 8 0 The C++ Language Tutorial try { // code here } catch (int param) { cout << "int exception"; } catch (char param) { cout << "char exception"; } catch (...) { cout << "default exception"; } " char ' throw $ int $ $ ! try.catch / " $ try.catch $ catch = $ " try ! $ $ throw; 8 try { try { // code here } catch (int n) { throw; } } catch (...) { cout << "Exception occurred"; } 86 ; throw $ $ 8 float myfunction (char param) throw (int); myfunction $ float ! " = char int " int& $ ! ! throw throw 4 $ $ 6 $ 8 int myfunction (int param) throw(); // no exceptions allowed int myfunction (int param); // all exceptions allowed 6 " ) exception <exception> ! what & # ! 4char *6 $ 0 % namespace std $ The C++ Language Tutorial // standard exceptions #include <iostream> #include <exception> using namespace std; My exception happened. class myexception: public exception { virtual const char* what() const throw() { return "My exception happened"; } } myex; int main () { try { throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0; } ; $ ' $ std::exception $ 4 myex ) 6! & myexception % $ 8 6 T T T $ T T 88 = % exception! T $ ! . ! new $ bad_alloc 8 try { int * myarray= new int[1000]; } catch (bad_alloc&) { cout << "Error allocating memory." << endl; } " $ ! $ J B " ! 0 bad_alloc bad_alloc $ int exception! exception 8 0 ! bad_alloc $ $ The C++ Language Tutorial // bad_alloc standard exception #include <iostream> #include <exception> using namespace std; int main () { try { int* myarray= new int[1000]; } catch (exception& e) { cout << "Standard exception: " << e.what() << endl; } return 0; } 0 * The C++ Language Tutorial $ ; 8 $ " = short a=2000; int b; b=a; : ! # 8 $ a short ) & int 4short int! int ) bool! ! int float! double ! $ " ! = $ 8 class A {}; class B { public: B (A a) {} }; A a; B b=a; : ! % % 86 class A class B! A B A B $ & ! # $ & 8 short a=2000; int b; b = (int) a; b = int (a); , ! ; $ 8 // c.like cast notation // functional notation $ : ! ! = 8 0 2 $ ! 6! The C++ Language Tutorial // class type.casting #include <iostream> using namespace std; class CDummy { float i,j; }; class CAddition { int x,y; public: CAddition (int a, int b) { x=a; y=b; } int result() { return x+y;} }; int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd.>result(); return 0; } % CAddition! & 8 $ padd = (CAddition*) &d; $ & ! # & result " dynamic_cast! reinterpret_cast! static_cast & 4<>6 ! $ ! const_cast $ 8 dynamic_cast <new_type> (expression) reinterpret_cast <new_type> (expression) static_cast <new_type> (expression) const_cast <new_type> (expression) & # $ 8 (new_type) expression new_type (expression) 8 H % dynamic_cast % " # ! dynamic_cast 8 0 5 The C++ Language Tutorial class CBase { }; class CDerived: public CBase { }; CBase b; CBase* pb; CDerived d; CDerived* pd; pb = dynamic_cast<CBase*>(&d); pd = dynamic_cast<CDerived*>(&b); // ok: derived.to.base // wrong: base.to.derived & & dynamic_cast ; $ ! dynamic_cast % # 8 // dynamic_cast #include <iostream> #include <exception> using namespace std; Null pointer on second type. cast class CBase { virtual void dummy() {} }; class CDerived: public CBase { int a; }; int main () { try { CBase * pba = new CDerived; CBase * pbb = new CBase; CDerived * pd; pd = dynamic_cast<CDerived*>(pba); if (pd==0) cout << "Null pointer on first type.cast" << endl; pd = dynamic_cast<CDerived*>(pbb); if (pd==0) cout << "Null pointer on second type.cast" << endl; } catch (exception& e) {cout << "Exception: " << e.what();} return 0; } dynamic_cast # > & " 4> "6 ) dynamic_cast % CBase* 4pba ? ( CDerived*! pbb6 8 CBase * pba = new CDerived; CBase * pbb = new CBase; A ! CDerived! CDerived % CDerived! pbb dynamic_cast! pba CBase! & CBase % ; % CBase*! pba % % pbb % dynamic_cast $ # & " dynamic_cast bad_cast & ! $ ! dynamic_cast 4void*6 0 1 % The C++ Language Tutorial H ! static_cast ! % % ! % ! ! & class CBase {}; class CDerived: public CBase {}; CBase * a = new CBase; CDerived * b = static_cast<CDerived*>(a); ! dynamic_cast % b & static_cast $ ! 8 double d=3.14159265; int i = static_cast<int>(d); $ 9 9 H ! reinterpret_cast ' 8 " & ! reinterpret_cast & & class class A * a B * b = A B = = $ & ! 8 {}; {}; new A; reinterpret_cast<B*>(a); ! % static_cast ! ! ! H % ! $ = & 0 3 8 $ ! The C++ Language Tutorial // const_cast #include <iostream> using namespace std; sample text void print (char * str) { cout << str << endl; } int main () { const char * c = "sample text"; print ( const_cast<char *> (c) ); return 0; } $ typeid 8 typeid (expression) % type_info <typeinfo> == & name() // typeid #include <iostream> #include <typeinfo> using namespace std; int main () { int * a,b; a=0; b=0; if (typeid(a) != { cout << "a and cout << "a is: cout << "b is: } return 0; } ; typeid a and b are of different types: a is: int * b is: int typeid(b)) b are of different types:\n"; " << typeid(a).name() << '\n'; " << typeid(b).name() << '\n'; typeid > " $ % != # % ! 8 0 0 ; The C++ Language Tutorial // typeid, polymorphic class #include <iostream> #include <typeinfo> #include <exception> using namespace std; a is: class CBase * b is: class CBase * *a is: class CBase *b is: class CDerived class CBase { virtual void f(){} }; class CDerived : public CBase {}; int main () { try { CBase* a = new CBase; CBase* b = new CDerived; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; cout << "*a is: " << typeid(*a).name() << '\n'; cout << "*b is: " << typeid(*b).name() << '\n'; } catch (exception& e) { cout << "Exception: " << e.what() << endl; } return 0; } ( CBase *6 : ! 4 typeid typeid % % " typeid ! typeid 4 *a *b6 typeid 6 4*6! bad_typeid $ 0 a b class 4 The C++ Language Tutorial < $ 7 4#6 $ ! $ ' ( $ 4J6 ! $ 4\6 &' -' ( #define " 8 #define identifier replacement ; replacement ! $ replacement identifier ! ! ! identifier replacement #define TABLE_SIZE 100 int table1[TABLE_SIZE]; int table2[TABLE_SIZE]; ' # TABLE_SIZE! 8 int table1[100]; int table2[100]; Y ! #define 8 #define getmax(a,b) a>b?a:b $ getmax ! $ $ // function macro #include <iostream> using namespace std; 8 5 7 #define getmax(a,b) ((a)>(b)?(a):(b)) int main() { int x=5, y; y= getmax(x,2); cout << y << endl; cout << getmax(7,x) << endl; return 0; } - ' Y 8 0 ! The C++ Language Tutorial #define TABLE_SIZE 100 int table1[TABLE_SIZE]; #undef TABLE_SIZE #define TABLE_SIZE 200 int table2[TABLE_SIZE]; 8 int table1[100]; int table2[200]; = " 4# # ##6 # # 4 # 8 ! 6 #define str(x) #x cout << str(test); 8 cout << "test"; 8 ## #define glue(a,b) a ## b glue(c,out) << "test"; 8 cout << "test"; B $ ! $ ! $ &' ' ! 8 $ -' -' -' ( #ifdef ! = $ 8 #ifdef TABLE_SIZE int table[TABLE_SIZE]; #endif " #define! #ifndef ! int table[TABLE_SIZE]; " ! $ 8 = #ifndef $ 8 0 TABLE_SIZE #endif $ -' The C++ Language Tutorial #ifndef TABLE_SIZE #define TABLE_SIZE 100 #endif int table[TABLE_SIZE]; " ! ! 033 " ! TABLE_SIZE $ #define $ #if! #else #elif 4 !9 96 #if $ ! $ = $ #elif 8 #if TABLE_SIZE>200 #undef TABLE_SIZE #define TABLE_SIZE 200 #elif TABLE_SIZE<50 #undef TABLE_SIZE #define TABLE_SIZE 50 #else #undef TABLE_SIZE #define TABLE_SIZE 100 #endif int table[TABLE_SIZE]; ( #if! #elif #ifdef #if #ifndef #elif #else #endif defined !defined 8 #if !defined TABLE_SIZE #define TABLE_SIZE 100 #elif defined ARRAY_SIZE #define TABLE_SIZE ARRAY_SIZE int table[TABLE_SIZE]; % &' ( ; ! ! #line ! " 8 #line number "filename" ; $ number = "filename" 0 $ 8 The C++ Language Tutorial #line 20 "assigning variable" int a?; 3 "assigning variable"! 8 $ &' ( ! 8 #ifndef __cplusplus #error A C++ compiler is required! #endif $ 4 __cplusplus 6 &' ( ; #include 8 #include "file" #include <file> $ 4 6 &# " ! " " & ! <> ! & # < $ &' ( #pragma " #pragma! & < 8 $ TT<"(ATT TT="<ATT TT-' ATT TT ",ATT " ' ' ' ' 9 8 9 ' " # TT = 9, 9 8 $ 8 0 * 011200< ! The C++ Language Tutorial // standard macro names #include <iostream> using namespace std; int main() { cout << "This is the line number " << __LINE__; cout << " of file " << __FILE__ << ".\n"; cout << "Its compilation began " << __DATE__; cout << " at " << __TIME__ << ".\n"; cout << "The compiler gives a __cplusplus value of "; cout << __cplusplus; return 0; } 0 2 This is the line number 7 of file /home/jay/stdmacronames.cpp. Its compilation began Nov 1 2005 at 10:12:29. The compiler gives a __cplusplus value of 1 The C++ Language Tutorial C++ Standard Library /) C 8 ) ) ) C % 8 cin istream! istream % ! cin < . $ ostream ; cout ' % ! ostream cout! 8 // basic file operations #include <iostream> #include <fstream> using namespace std; [file example.txt] Writing this to a file int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } example.txt myfile cout! B . 8 ) % ' % ! $ myfile6 % " % open()8 open (filename, mode); ; filename 6 & # const char * 4 ! mode 8 0 5 4 The C++ Language Tutorial 88 88 88 88 88 88 ) " ! ' ! & " $ ' example.bin ! > 4|6 = $ ! open()8 ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); A open() ofstream! ifstream fstream 8 88 88 88 = W ifstream 88 ofstream ! ios::in ! ios::out open() " ! = ( & ! 4 6 ) % ! $ open() ! myfile $ % 8 ofstream myfile ("example.bin", ios::out | ios::app | ios::binary); % B # ! ! is_open() % 8 if (myfile.is_open()) { /* ok, proceed with output */ } 0 1 The C++ Language Tutorial ; " . close() 8 ! myfile.close(); ! " % ! % close() ! 6 $ ios::binary $ C ! - $ // writing on a text file #include <iostream> #include <fstream> using namespace std; cout8 [file example.txt] This is a line. This is another line. int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } - cin8 0 3 The C++ Language Tutorial // reading a text file #include <iostream> #include <fstream> #include <string> using namespace std; This is a line. This is another line. int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; } $ ! $ eof() ( ; 4 myfile.eof() ! 6 F " ! eof()! 4 $ 68 &( > = $ &( > 46! ! $ &( > &( " 8 " % clear()! ' C ifstream! % ! ! 8 $ istream! 0 0 The C++ Language Tutorial ofstream! $ ostream! = ! fstream! istream ostream6 ! ! iostream 4 8 !" !" pos_type! tellg6 4 4 tellp6 !" !" B 8 seekg ( position ); seekp ( position ); K position 4 tellg 6 tellp8 pos_type! 8 seekg ( offset, direction ); seekp ( offset, direction ); K ' ! direction offset seekdir! direction off_type! 4enum6 8 ! 88 88 88 $ % 0 ? 8 The C++ Language Tutorial // obtaining file size #include <iostream> #include <fstream> using namespace std; size is: 40 bytes. int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end.begin) << " bytes.\n"; return 0; } = " getline $ = write ! $ 4<< ! >>6 ! 4 ! ! 6 # 4write6 read istream ofstream ' ostream ifstream % 8 read fstream 8 write ( memory_block, size ); read ( memory_block, size ); ; memory_block 9 9 4char*6! size C // reading a complete binary file #include <iostream> #include <fstream> using namespace std; the complete file content is in memory ifstream::pos_type size; char * memblock; int main () { ifstream file ("example.bin", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout << "the complete file content is in memory"; delete[] memblock; } else cout << "Unable to open file"; return 0; } " $ < . 0 $ 8 The C++ Language Tutorial = ! ios::ate ! ! tellg()! ? ( size8 ifstream::pos_type size; ifstream::pos_type file.tellg() ! ! ? = ? FB int8 int size; size = (int) file.tellg(); ? ! # 8 memblock = new char[size]; > ! 4 6! ! 8 file.seekg (0, ios::beg); file.read (memblock, size); file.close(); ' = ! ; ! put 4 ofstream! 6 " streambuf = $ ! ! ! . ; ! 4 4 6 6 8 E ? E B ? ; ? 86 86 ? ; ! 8 flush - &( ! . ? int 4 ? 6 0 0 $ endl sync()! # .1