slide ki thuat lap trinh

Upload: le-quang

Post on 10-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    1/203

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    2/203

    2

    4.2 THE if-else STATEMENT 4.3 NESTED if STATEMENT 4.4 THE switch STATEMENT 4.5 CONDITIONAL EXPRESSIONS 4.6 THE enum SPECIFIER

    Chapter 5 REPITITION STRUCTURES 5.1 INTRODUCTION 5.2 while LOOPS 5.3 INTERACTIVE while LOOP 5.4 for LOOPS 5.5 NESTED LOOPS 5.6 do-while LOOPS 5.7 STRUCTURED PROGRAMMING WITH C++ 5.8 ARRAYS 5.9 STRUCTURES

    Chapter 6 MODULARITY USING FUNCTIONS 6.1 FUNCTION AND PARAMETER DECLARATIONS 6.2 RETURNING VALUES 6.3 VARIABLE SCOPE 6.4 VARIABLE STORAGE CLASS. 6.5 PASS BY REFERENCE USING REFERENCEPARAMETERS 6.6 RECURSION 6.7 PASSING ARRAYS TO FUNCTIONS 6.8 POINTERS

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    3/203

    3

    6.9 PASSING STRUCTURES as PARAMETERS 6.10 THE typedef DECLARATION STATEMENT

    Chapter 7 INTRODUCTION TO CLASSES 7.1 STACK VERSUS HEAP

    7.2 OBJECT ORIENTED PROGRAMMING AND CLASSES 7.3 INFORMATION HIDING 7.4 MEMBER FUNCTIONS

    Chapter 8 OBJECT MANIPULATION 8.1 ADVANCED CONSTRUCTORS

    8.2 DESTRUCTORS 8.3 ASSIGNMENT 8.4 CONSTANT OBJECTS 8.5 STATIC CLASS MEMBERS

    Chapter 9 INHERITANCE POLYMORPHISM -TEMPLATE

    9.1 BASIC INHERITANCE 9.2 OVERRIDDING BASE CLASS MEMBER FUNCTIONS 9.3 CONSTRUCTORS AND DESTRUCTORS IN DERIVEDCLASSES 9.4 POLYMORPHISM 9.5 TEMPLATES 9.6 PURE VIRTUAL FUNCTIONS AND ABSTRACT BASECLASSES

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    4/203

    4

    Chapter 1 INTRODUCTION TO COMPUTER AND

    PROGRAMMING

    1.1 HARDWARE AND SOFTWARE

    1.1.1 Computer HardwareA computer may be divided into six logical units.

    Input Unit y O btain information from input devices: keyboards and mouse

    devices.y Place the information at the disposal of the other units to be

    processed.

    Output Unit y Take information that has been processed.y Place it on output devices: displayed on screens, printed on

    paper.

    Mem ory Unit y RA M ( random access memory ) is volatile, stores program and

    data.y RO M ( read only memory ) is non-volatile, contains fundamental

    instructions.

    A rith me tic and Logic Unit ( A LU)

    y Perform all the arithmetic and logic operations: addition,subtraction, comparison, etc..

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    5/203

    5

    CP U y Tell the input unit when information should be read into the

    memory unit.y Tell the ALU when information from the memory should be

    used in calculations.y Tell the output unit when to send information from the memory

    unit to certain output devices.

    S econdary S torag e .y Permanent storage areas for programs and data: magnetic tapes,

    magnetic hard disks, floppy disk, CD RO M

    1.1.2 Computer Softwarey A com put er progra m: set of instructions used to operate a

    computer to produce a specific result.y C om put er progra mm ing : writing computer programs.y P rogra mm ing languag es: languages used to create computer

    programs.

    M achin e Languag esExample: 0101010 000000000001 000000000010

    y The lowest level of computer languages.y Programs consist of entirely of 1s and 0s.y Programs can control directly to the computers hardware.y Machine language instructions consist of two parts:

    o I nstruction part ( opcode ) is the leftmost group of bits andtells the computer the operation to be performed.

    o A ddress part specifies the memory address of the data to beused in the instruction.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    6/203

    6

    A ssemb ly Languag es

    Example:LOA D B AS EPAY ADD OV ER PAY STOR E G ROSS PAY

    y Perform the same tasks as machine languages, but use symb olicna me s for opcodes and operands.

    y An assembly language program must be translated into amachine language program.

    y Machine languages and assembly languages are called low-l eve l languag es since they are clos est to co m put er hardwar e.

    H igh-l eve l P rogra mm ing Languag es

    y Create computer programs using instructions that much easier to understand: E nglish-lik e included with mathematicalnotations.

    y Programs written in high-level languages must be translatedinto a low level language using a program called a co m pil er .

    y Each line in a high-level language program is called a

    statement .Ex: R esult = (First + Second)* Third.

    A pplication and S yst em S oftwar e y A pplication software: perform particular tasks required by the

    users.

    Translation program(assembler)

    Assemblylanguage program

    Machinelanguage program

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    7/203

    7

    y S ystem software: must be available to any computer system tooperate. The most important system software is the operating

    system (MS-DOS , UN IX , MS WI NDOWS , MS W I NDOWS NT )

    y Mu ltitasking systems: operating systems allow user to run

    multiple programs.1.2 PROGRAMMING LANGUAGESFORTRAN 1957COBOL 1960sBAS I C 1960sPAS CAL 1971 Structure programmingCC++C and C++ are two separate, but related programming languages.I n the 1970s, at Bell Laboratories, Dennis R itchie and BrianKernighan designed the C programming language.In 1985, at Bell Laboratories, Bjarne Stroutrup created C++ basedon the C language. C++ is an extension of C that adds object-

    oriented programming capabilities.

    W hat is S yntax?y Set of rules for writing grammatically correct language

    statements.

    1.2.1 The C Programming Languagey C was used exclusively on UN IX and on mini-computers.

    During the 1980s, C compilers were written for other flatforms,including PCs.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    8/203

    8

    y To provide a level of standardization for C language, in 1989,ANS I created a standard version of C that is called AN S I C .

    y One m ain be ne fit of the C language is that it is much clos er toass emb ly languag e other than other types of high-level

    programming languages. The programs written in C often run

    much fast er and more efficiently.1.2.2 The C++ Programming Language

    y C++ is now the most popular programming language for writinggraphical programs that run on Windows and Macintosh.

    y The standardized version of C++ is commonly referred to as AN S I C++ .

    y The ANS I standards also define run-ti me li brari es, whichcontains useful functions, variables, constants, and other

    programming items that you can add to your programs.y The ANS I C++ run-time library is also called the S tandard

    T em plat e Li brary or Standard C++ Library.

    1.2.3 Microsoft Visual C++y Actually, V isual C++ itself is not a programming language. I t is

    a d eve lop me nt environ me nt used for creating programs withthe C/C++ languages.

    y V isual C++ extends the C++ language by allowing you toinclude M icrosoft Foundation C lass es in your programs.

    1.3 PROBLEM SOLUTION AND SOFTWAREDEVELOPMENT

    Software development consists of three overlapping phases:y Development and Designy Documentation

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    9/203

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    10/203

    10

    P has e III : M aint enanc e This phase is concerned with the ongoing correction of problems,revisions to meet changing needs and the addition of new features.

    1.4 ALGORITHMS

    1.4.1 FlowchartsA flowchart is an outlin e of the basic structur e or logic of the

    program.

    Terminal

    I nput/output

    Process

    Flow lines

    Decision

    Connector

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    11/203

    11

    Predefined process

    Note: Name, Hours and Pay are variables in the program.

    1.4.2 Pseudo-codeYou also can use English-like phases to desribe an algorithm. I n thiscase, the description is called pse u do-code .

    Inp u t the three val u es into the variables Name, Ho u rs, Rate.

    Calc u late Pay = Ho u rs v Rate. Display Name and Pay.

    Problem 1.Write a program to do the following task: Print a list of the numbersfrom 4 to 9. Next to each number, print the square of the number.

    Start

    Input Name,H ur Rate

    CalculatePay n Hours v Rate

    DisplayName, Pay

    End

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    12/203

    12

    Note:

    1. Loop is a very important concept in programming.2. Num n Num + 1

    New value of Num = old value of Num + 1.

    Start

    NUM n 4

    SQNUM n NUM 2

    PrintNUM, SQNUM

    NUM n NUM + 1

    NUM

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    13/203

    13

    Since flowcharts are inconvenient to revise, they have fallen out of favor by programmers. Nowadays, the use of pseudocode has gainedincreasing acceptance.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    14/203

    14

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    15/203

    15

    Chapter 2 PROBLEM SOLVING USING C++

    2.1 INTRODUCTION TO C++

    2.1.1 Modular Programsy M odul es: interrelated segments, arranged in a logical order.y A program that consists of such modules is called a modular

    program.y I n C++ , modules can be class es or functions .

    Function : transform the data it receives into a result. Each function

    must have a name. Names or id entifi ers in C++ can made up of anycombination of letters, digits, or underscores selected according tothe following rules:

    y I dentifiers must begin within an uppercase or lowercase AS CII letter or an underscore (_).

    y You can use digits in an identifier, but not as the first character.Y

    ou are not allowed to use special characters such as $, &, * or %.y R eserved words cannot be used for variable names.

    Examples of valid identifiers:Deg ToR ad intersect add NumsFindMax1 _density slope

    Examples of invalid identifiers:1AB3 E%6 while

    Note: C++ is a cas e-sensiti ve language.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    16/203

    16

    2.1.2 The m ain() functiony The m ain () function: runs automatically when a program first

    executes.y C++ programs must include on e m ain() function. A ll other

    functions in a C++ program are executed from the main () function.

    The first line of the function, in this case void main () is called a function h ead er lin e.The f u nction header line contains three pieces of information:

    1. What type of data, if any, is returned from the function?2. The name of the function.3. What type of data, if any, is sent into the function?

    int main(){

    program statements in herereturn 0;

    }O r void main(){

    program statements in here}

    2.1.3 The cout ObjectThe co u t object: an output object that sends data given to it to thestandard output display device.

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    17/203

    17

    The ins ertion op erator ,

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    18/203

    18

    C++ stat eme nts writing syntax : A ll statements in C++ must end with a s em icolon .Large statements can span m ultipl e lin es of cod e:cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    19/203

    19

    y There are three basic data types used in C++: integers, floating point numbers and characters.

    Int e g ersy An integer is a positive or negative number with no decimal

    places.- 259 -13 0 200

    Floating P oint N umbe rsy A floating point number contains decimal places or is written

    using exponential notations.-6.16 -4.4 2.7541 10.5

    y Ex ponential notation or scientific notation is a way of writing avery large numbers or numbers with many decimal places usinga shortened format.2.0e11 means 2*10 11

    y C++ supports three different kinds of floating-point numbers:o float (i.e. single precision numbers),o double (i.e. double precision numbers)o long double.

    Th e C haract er Data Typ e y To store text, you use the character data type. To store one

    character in a variable, you use the char keyword and place thecharacter in single quotation marks.

    char letter = A;

    E scap e S eq uenc e The combination of a backlash (\) and a special character is calledan escape sequence.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    20/203

    20

    \n move to the next line\t move to the next tab

    2.3.2 Arithmetic OperatorsO perator Description

    ---------------------------------------------------------------+ Add two operands- Subtracts one operand from another operand* Multiplies one operand by another operand/ Divides one operand by another operand% Divides two operands and returns the remainder

    A simple arithmetic expression consists of an arithmetic operator connecting two operands in the form:

    operand operator operand

    3 + 712.62 + 9.812.6/2.0

    Example 2.3.1# include void main(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    21/203

    21

    Int e g er Di vision

    Th e di vision of two int e g ers yields integer result. Thus the value of 15/2 is 7.

    15.0/2 is ???Modulus % operator produces the remainder of an integer division.

    9%4 is 117%3 is 214%2 is 0

    O perator P r eced enc e and A ssociati vity

    Expressions containing multiple operators are evaluated by the

    priority, or precedence , of the operators.The following table lists both precedence and associativity of theoperators.

    O perator Associativity---------------------------------unary - R ight to left

    * / % Left to right+ - Left to right

    8 + 5*7%2*4q q q q

    4 1 2 3

    2.4 VARIABLES AND DECLARATION STATEMENTSOne of the most important aspects of programming is storing and manipulating the values stored in variables .V aria bl e na me s are also selected according to the rules of identifiers:

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    22/203

    22

    y I dentifiers must be gin with an uppercase or lowercase AS CII letter or an underscore (_).

    y You can use digits in an identifier, but not as the first character.You are not allowed to use sp ecial charact ers such as $, &, * or %.

    y R eser ved words cannot be used for variable names.Example: Some valid identifiers

    my_variable Temperature x1x2 _my_variable

    Some in valid identifiers are as follows:%x1 %my_var @x2

    2.4.1 Declaration StatementsI n C++ you can declare the data types of variables using the syntax:

    type na me; The type portion refers to the data type of the variable. The data typedetermines the type of information that can be stored in the variable.

    Example:int sum;long datenem;double secnum;

    Note:1. A varia bl e must be d eclar ed be for e it can be us ed .2. Declaration statements can also be used to store an initial valu e

    into declared variables.Example:

    int num = 15;

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    23/203

    23

    float grade1 = 87.0;Example 2.4.1# include void main(){

    float grade1 = 85.5;float grade2 = 97.0;float total, average;total = grade1 + grade2;average = total/2.0; // divide the total by 2.0cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    24/203

    24

    num = 22;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    25/203

    25

    Name Namesint * signed,

    signed intSystem dependent

    unsignedint

    * unsigned System dependent

    bool 1 none false or truechar 1 signed char 128 to 127unsignedchar

    1 none 0 to 255

    short 2 short int,signed shortint

    32,768 to 32,767

    unsignedshort

    2 unsignedshort int

    0 to 65,535

    long 4 long int,signed longint

    2,147,483,648 to 2,147,483,647

    long long 8 none (butequivalent to

    __int64)

    9,223,372,036,854,775,808 to9,223,372,036,854,775,807

    unsignedlong

    4 unsignedlong int

    0 to 4,294,967,295

    enum * none Same as intfloat 4 none 3.4E +/- 38 (7 digits)double 8 none 1.7E +/- 308 (15 digits)

    long double same asdouble none same as double

    wchar_t 2 __wchar_t 0 to 65,535

    The limits for integer types are listed in the following table. Theselimits are defined in the standard header file LI M IT S . H .

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    26/203

    26

    Limits on Integer Constants

    Constant Meaning ValueSCHAR_MIN Minimum value for a

    variable of type signedchar .

    128

    SCHAR_MAX Maximum value for avariable of type signedchar .

    127

    UCHAR_MAX Maximum value for avariable of type unsignedchar .

    255 (0xff)

    CHAR_MIN Minimum value for avariable of type char .

    128

    CHAR_MAX Maximum value for avariable of type char .

    127

    SHRT_MIN Minimum value for avariable of type short .

    32768

    SHRT_MAX Maximum value for a

    variable of type short .

    32767

    USHRT_MAX Maximum value for avariable of type unsignedshort .

    65535 (0xffff)

    INT_MIN Minimum value for avariable of type int .

    2147483647 1

    INT_MAX Maximum value for a

    variable of type int .

    2147483647

    UINT_MAX Maximum value for avariable of type unsignedint .

    4294967295 (0xffffffff)

    LONG_MIN Minimum value for a 2147483647 1

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    27/203

    27

    variable of type long .LONG_MAX Maximum value for a

    variable of type long .2147483647

    ULONG_MAX Maximum value for avariable of type unsigned

    long .

    4294967295 (0xffffffff)

    2.4.4 Data Type Conversionsy An expression that contains only integer operands is called an

    int e g er e xpr ession , and the result of the expression is an integer value.

    y An expression that contains only floating point operands (single

    and double precision) is called a floating point e xpr ession , andthe result of such an expression is a floating point value.

    y An expression containing both integer and floating pointoperands is called a m ix ed m od e e xpr ession .

    The general rul es for con verting integer and floating pointoperands in mixed mode arithmetic expressions were presented asfollows:1. I f both op erands are either charact er or int e g er operands:

    a. when both operands are charact er , short or integer datatypes, the result of the expression is an integer value.

    b. when one of the operand is a long int e g er , the result is a longinteger, unless one of the operand is an unsign ed int e g er . I nthe later case, the other operand is converted to an unsignedinteger value and the resulting value of the expression is anunsigned value.

    2. I f any one op erand is a floating point value:a. when one or both operands are floats, the result of the

    operation is a float value;

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    28/203

    28

    b. when one or both operands are doubles, the result of theoperation is a double value;

    c. when one or both operands are long doubles, the result of theoperation is a long double value;

    2.4.5 Determing Storage SizeC++ provides an operator for determining the amount of storageyour compiler allocates for each data type. This operator, called thesiz eof() operator.

    sizeof(num1)sizeof(int)sizeof(float)

    The item in parentheses can be a varia bl e or a data typ e .

    # include void main(){

    char ch;short int num1;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    29/203

    29

    Bytes of storage used by a short integer: 2

    2.5 SOME SAMPLE PROGRAMS

    2.5.1 Computing the circumference of a circle

    C = 2 Tr

    # include void main(){

    float radius, circumference;radius = 2.0;circumference = 2.0 * 3.1416 * radius;

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    30/203

    30

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    31/203

    31

    Chapter 3 COMPLETING THE BASICS

    3.1 ASSIGNMENT OPERATORS A ssignment operator (=) are used for assignment a value to a

    variable and for performing computations.Assignment statement has the syntax:varia bl e = e xpr ession ;

    Ex pression is any combination of constants, variables, and functioncalls that can be evaluated to yield a result.

    length = 25;

    cMyCar = Mercedes;sum = 3 + 7;newtotal = 18.3*amount;slope = (y2 y1)/(x2 x1)

    I ts important to note that the eq ual sign in C ++ does not have thesame meaning as an equal sign in mathematics.

    Example 3.1// this program calculates the volume of a cylinder,// given its radius and height# include void main(){

    float radius, height, volume;radius = 2.5;height = 16.0;volume = 3.1416 * radius * radius * height;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    32/203

    32

    }The output of the above program:The volume of the cylinder is 314.16 Note:

    We can write m ultipl e assign me nts : a = b = c = 25;

    A ssign me nt V ariations

    C++ includes other arithmetic operators in addition to the equal sign.

    O perator Example Meaning-------------------------------------------- -------------------------= i Num1 = i Num2+= i Num1 += i Num2 i Num1 = i Num1 + i Num2-= i Num1 -= i Num2 i Num1 = i Num1 - i Num2*= i Num1 *= i Num2 i Num1 = i Num1 * i Num2/= i Num1 /= i Num2 i Num1 = i Num1 / i Num2

    %= i Num1 %= i Num2 i Num1 = i Num1 % i Num2

    Assignment statements such as sum += 10 or its equivalent, sum =sum + 10, are very common in programming.

    Incr eme ntal and d ecr eme ntal op erators

    O perator Description---------------------------------------------------------------

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    33/203

    33

    ++ I ncrease an operand by a value of one-- Decrease an operand by a value of one

    The increment (++) and decrement (--) unary operators can be usedas prefix or postfix operators to increase or decrease value.

    y A pr e fix operator is placed before a variable and returns thevalue of the operand after the operation is performed.

    y A postfix operator is placed after a variable and returns thevalue of the operand before the operation is performed.

    Prefix and postfix operators have different effects when used in astatement

    b = ++a;will first increase the value of a to 6, and then assign that new valueto b. I t is equivalent to

    a = a +1; b = a;

    On the other hand, execution of the statement b = a++;

    will first assign the value of 5 to b, and then increase the value of ato 6. I t is now equivalent to

    b = a;a = a + 1;

    The decrement operators are used in a similar way.

    3.2 FORMATTING NUMBER FOR PROGRAM OUTPUT3.2.1 Stream ManipulatorsS tream manip u lator functions are special stream functions thatchange certain characteristics of the input and output.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    34/203

    34

    The main advantage of using manipulator functions is they facilitatethe formatting of the input and output streams.

    y setw() : stands for set width . This manipulator is used to specifythe minimum number of the character positions on the outputfield a variable will consume.

    y setpr ecision() : is used to control the number of digits of anoutput stream display of a floating point value. S etprecision (2) means 2 digits of precision to the right of the decimal point.

    # include int main(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    35/203

    35

    o setiosflags ( ios::fi xed ) means the output field will useconventional fixed-point decimal notation.

    o setiosflag ( ios::showpoint ) means the output field will showthe decimal point for floating point number.

    o setiosflags ( ios::scientific ) means the output field will use

    exponential notation.Example:cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    36/203

    36

    // a progran to illustrate output conversions# include # include void main(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    37/203

    37

    The output of the above program:The decimal value of 025 is 21The decimal value of 0x37 is 55

    3.3 USING MATHEMATICAL LIBRARY FUNCTIONS

    I f your program uses mathematic function sqrt () , it should have the preprocessor command # includ e< m ath.h> in the beginning of the program. This makes a mathematical library accessible.

    Function Name Description R eturn Value-----------------------------------------------------------------abs(a) A bsolute value Same data type as argumentlog(a) Natural logarithm doublesin(a) sine of a (a in radians) doublecos(a) cosine of a (a in radians) doubletan(a) tangent of a (a in radians) doublelog10(a) common log (base 10) of a double

    pow(a1,a2) a1 raised to the a2 power doubleexp(a) e a doublesqrt(a) square root of a double

    Table 3.2 Some mathematical built-in functionsExcept abs ( a ) , they all take an argument of type do u ble and return avalue of type do u ble .Example 3.3.1# include

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    38/203

    38

    # include void main(){

    int height;double time;height = 800;time = sqrt(2 * height / 32.2); // gravitational constant g =

    32.32cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    39/203

    39

    3.4 PROGRAM INPUT USING THE cin OBJECT

    3.4.1 Standard Input StreamThe cin object reads in information from the keyboard via thestandard input stream.The e xtraction op erator (>>) retrieves information from the inputstream.# include void main(){

    float num1, num2, product;cout > num1;cout > num2;product = num1 * num2;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    40/203

    40

    cout > num1 >> num2 >> num3;average = (num1 + num2 + num3) / 3.0;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    41/203

    41

    total = amount + taxes;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    42/203

    42

    The strcat () function combines two strings using the syntax:strcat(d estination, sourc e );

    The functions listed in Table 3.3 are contained in the string.h header file. To use the functions, you must add the statement# incl u de to your program.

    # include # include

    int main( void )

    {char string[80];strcpy( string, "Hello world from " );strcat( string, "strcpy " );strcat( string, "and " );strcat( string, "strcat!" );

    printf( "String = %s\n", string );}Output:String = Hello world from strcpy and strcat!

    # include # include char string1[] = "The quick brown dog jumps over the lazyfox";char string2[] = "The QUICK brown dog jumps over the lazyfox";

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    43/203

    43

    int main( void ){

    char tmp[20];int result;/* Case sensitive */printf( "Compare strings:\n %s\n %s\n\n", string1, string2

    );result = strcmp( string1, string2 );if( result > 0 )

    strcpy( tmp, "greater than" );

    else if( result < 0 )strcpy( tmp, "less than" );else

    strcpy( tmp, "equal to" );printf( " strcmp: String 1 is %s string 2\n", tmp );/* Case insensitive (could use equivalent _stricmp) */result = _stricmp( string1, string2 );if( result > 0 )

    strcpy( tmp, "greater than" );else if( result < 0 )

    strcpy( tmp, "less than" );else

    strcpy( tmp, "equal to" );printf( " _stricmp: String 1 is %s string 2\n", tmp );

    }Output:Compare strings:

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    44/203

    44

    The quick brown dog jumps over the lazy foxThe QUICK brown dog jumps over the lazy foxstrcmp: String 1 is greater than string 2

    _stricmp: String 1 is equal to string 2

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    45/203

    45

    Chapter 4 SELECTION STRUCTURE

    The flow of control refers to the order in which a programsstatements are executed. The nor m al flow of control for all

    programs is seq uential . S el ection , r e petition and function in vocation structures permit theflow of control to be altered in a defined way.

    4.1 SELECTION CRITERIA

    C om parison O perators

    Comparison operators are used to compare two operands for

    equality and to determine if one numeric value is greater thananother.

    O perator Description---------------------------------------------------= = equal!= not equal

    > greater than< less than= greater than or equal

    Example:a = = b (a*b) != cs == y x

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    46/203

    46

    Logical O peratorsLogical operators are used for creating more complex conditions.

    O perator Description---------------------------------------------------&& AN D|| OR ! NOT

    Example:(age > 40) && (term < 10)(age > 40) || (term < 10)

    !(age > 40)( i==j) || (a < b) || complete

    4.2 THE if-else STATEMENTThe syntax for an if .. else statement:if (conditional expression) {

    statements;}else {

    statements;}

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    47/203

    47

    Figure 4.1 The flow chart of if-else statement

    Example 4.2.1# include # include

    const float LOWRATE = 0.02; // lower tax rateconst float HIGHRATE = 0.025; // higher tax rate

    const float CUTOFF = 20000.0; // cut off for low rateconst float FIXEDAMT = 400; // fixed dollar amount for higher rate amountsint main(){

    float taxable, taxes;cout > taxable;if (taxable

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    48/203

    48

    // set output formatcout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    49/203

    49

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    50/203

    50

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    51/203

    51

    Figure 4.2 The flow chart of one-way if statement

    Example 4.2.3# include int main(){

    const float LIMIT = 3000.0;int idNum;

    float miles;cout > idNum >> miles;if(miles > LIMIT)

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    52/203

    52

    Th e if- else C hain

    When an if statement is included in the else part of an existing if statement, we have an if-else chain .Example 4.3.1# include int main(){

    char marcode;cout > marcode;if (marcode == 'M')

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    53/203

    53

    {float monthlySales, income;cout > monthlySales;if (monthlySales >= 50000.00)

    income = 375.00 + .16 * monthlySales;else if (monthlySales >= 40000.00)

    income = 350.00 + .14 * monthlySales;else if (monthlySales >= 30000.00)

    income = 325.00 + .12 * monthlySales;else if (monthlySales >= 20000.00)

    income = 300.00 + .09 * monthlySales;else if (monthlySales >= 10000.00)

    income = 250.00 + .05 * monthlySales;else

    income = 200.00 + .03 * monthlySales;// set output format

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    54/203

    54

    4.4 THE switch STATEMENTThe switch statement controls program flow by executing a set of statements depending on the value of an expression. Note: The valu e of e xpr ession must be an int e g er data typ e, whichincludes the char, int , long int , and short data types.

    switch(expression){case label:

    statement(s);break;

    case label;statement(s);

    break;default:

    statement(s);}

    y What about bool data type???y The break statement causes an immediate exit from the switch

    statement.y What happens if the break statements are omitted???

    # include int main()

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    55/203

    55

    {int opselect;double fnum, snum;cout > fnum >> snum;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    56/203

    56

    Please type in two numbers: 12 3Enter a select code:

    1 for addition2 for multiplication3 for division : 2

    The product of the numbers entered is 364.5 CONDITIONAL EXPRESSIONSProvide an alternative way of expression a simple if-else statement.

    e xpr ession1 ? e xpr ession2 : e xpr ession3I f the value of e x pression1 is nonzero (true), e x presson 2 isevaluated; otherwise, e x pression3 is evaluated.The value for the complete conditional expression???Example: The if statement:

    if (hours > 40)rate = 0.45else

    rate = 0.02;can be replaced with:

    rate = (hours > 40) ? 0.45 : 0.02;

    4.6 THE enum SPECIFIER The enu m specifier create an enumerated data type.Example:

    enu m day { m on, tu e , w ed, thr, fri, sat, sun} ;

    enu m color {r ed, gr ee n, y ellow}; Any variable declared to be of type color can take only a value of red or green or yellow . S imiliarly for type day .

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    57/203

    57

    The statementenum day a, b,c;

    declares the variables a, b , and c to be of type day .# include void main(){

    enum color{red, green, yellow};enum color crayon = red;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    58/203

    58

    Chapter 5 REPITITION STRUCTURES

    5.1 INTRODUCTIONC++ provides three different forms of repetition structures:

    y while structurey for structurey do-while structure

    Each of these structures requires a condition that must be evaluated.y at the beginning of the loop: pre-test loop or entrance-controlled

    loop.y at the end of the loop: post-test loop or exit-controlled-loop.

    5.2 while LOOPSThe while statement is used for repeating a statement or series of statements as long as a given conditional expression is evaluated totrue.while( condition expression){

    statements;}Example 5.2.1# include void main(){

    int count;count = 1; // initialize countwhile (count

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    59/203

    59

    }}The output of the above program:1 2 3 4 5 6 7 8 9 10

    Figure 5.1 The flow chart of the while statement# include void main()

    {int i;i = 10;while (i >= 1){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    60/203

    60

    5.3 INTERACTIVE while LOOPCombining interactive data entry with the repetition capabilities of the while statement produces very adaptable and powerful programs.# include # include void main(){

    const int MAXNUMS = 4;int count;float num;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    61/203

    61

    The number entered is 5.000Enter a number: 103.456The number entered is 103.456Enter a number: 1267.89The number entered is 1267.890

    S entin elsI n programming, data values used to indicate either the start or endof a data series are called sentinels .Example 5.3.2# include

    const int HIGHGRADE = 100;void main(){

    float grade, total;grade = 0;total = 0;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    62/203

    62

    br eak stat eme nt The break statement causes an exit from the inn er m ost enclosingloop statement. while( count num;if (num > 76){

    cout 100)

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    63/203

    63

    continue;total = total + grade;count++;

    }

    Th e null stat eme nt

    A semicolon with nothing preceding it is also a valid statement,called the nu ll statement .if (a > 0)

    b = 7;else ;

    5.4 for LOOPSy The for statement is used for repeating a statement or series of

    statements as long as a given conditional expression evaluatesto true.

    y Main differences between while statement and for statement:included code in the for statement:

    o

    to initialize a counter variable ando changes its value with each iteration

    for ( initialization expression; condition; update statement){statement(s);

    }Example 5.4.1

    # include void main(){

    int count;for (count = 2; count

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    64/203

    64

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    65/203

    65

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    66/203

    66

    for(j = 1; j

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    67/203

    67

    do {cout> idNum;

    } while (idNum < 1000|| idNum> 1999);Here, a request for a new id-number is repeated until a valid number is entered.

    do {cout> idNum;if (idNum < 1000 || idNum > 1999)

    {cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    68/203

    68

    else break;} while (true);

    5.7 STRUCTURED PROGRAMMING WITH C++

    Th e goto S tat eme nt (khong n en dung goto)

    I n C++, goto statement an unconditional branch, is just a legacycode from C language. The result of the goto statement is a changein the flow of control of the program to the first statement after thela be l specified in the goto statement.

    start: // labelif (count > 10) go to end;

    go to start;end: cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    69/203

    69

    y The sequence structure is built into C++.y C++ provides three types of selection structures:

    o - if statement (single-selection structure)o - if-else statement (double-selection structure)o

    - switch statement. (multiple-selection structure)y C++ provides three types of repetition structures:o - while statemento - do-while statemento - for statement

    y We will see that each control structure has only one entry point

    and one e xit point . These single-entry / single-e xit control str u ct u res make it easy to build programs.

    y One way to build program is to connect the exit point of onecontrol structure to the entry point of the next. This way iscalled control-str u ct u re-stacking .

    y Another way is to place one control structure inside another control structure. This way is called control-str u ct u re-nesting .

    y Consistent applying reasonable indentation conventionsthroughout your programs greatly improves programreadability. We suggest a fixed-size three blanks per indent.

    y Using good control structures to build programs is one of themain principles of structured programming. Another principleof structured programming is top-down, stepwise refinement .

    Top-down, S t e pwis e R e fin eme nt

    Consider the following problem:Develop a class-averaging program that will process an

    arbitrary number of grades each time the program is run.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    70/203

    70

    First R efinement: Initialize variables

    Inp u t, s u m and co u nt the e xam grades

    Calc u late and print the class a verage

    Second R efinement: Inp u t the first gradeW hile the u ser has not as yet entered the sentinel

    Add this grade into the running total A dd one to the grade co u nter

    Inp u t the ne xt grade

    Calc u late and print the class a verage Third R efinement:

    Initialize total to zero Initialize co u nter to zero

    Inp u t the first grade W hile the u ser has not as yet entered the sentinel

    A dd this grade into the r u nning total A dd one to the grade co u nter

    Inp u t the ne xt grade

    If the co u nter is not eq u al to zero

    set the a verage to the total di vided by the co u nter

    print the a verageelse

    Print No grades were entered.

    Final step: We come to the following C++ program.# include

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    71/203

    71

    # include void main(){

    int total, // sum of gradesgradeCounter, // number of grades enteredgrade; // one grade

    double average; // number with decimal point for average

    // initialization phasetotal = 0;gradeCounter = 0;

    // processing phasecout > grade;while ( grade != -1 ) {

    total = total + grade;

    gradeCounter = gradeCounter + 1;cout > grade;

    }// termination phaseif ( gradeCounter != 0 ) {

    average = double ( total ) / gradeCounter;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    72/203

    72

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    73/203

    73

    }The output is:

    AB

    CDF

    # include int main()

    {const int MAXGRADES = 5;int i, grade[MAXGRADES], total = 0;cout grade[i];

    }

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    74/203

    74

    return 0;}

    5.8.2 Multi-Dimensional Arraysy The C++ language allows arrays of any type, including arrays

    of arrays.int a[1000]; // a one-dimensional arrayint b[3][5]; // a two-dimensional arrayint c[7][9][2]; // a three-dimensional arrayI n these above example, b has 3 v 5 elements, and c has 7 v 9 v 2elements. Starting at the base address of the array, all the array

    elements are stored contig u

    ou sly in memory.y For the array b, we can think of the array elements arranged as

    follows:col 1 col2 col3 col4 col5

    row 1 b[0][0] b[0][1] b[0][2] b[0][3]b[0][4]

    row 2 b[1][0] b[1][1] b[1][2] b[1][3]b[1][4]

    row 3 b[2][0] b[2][1] b[2][2] b[2][3]b[2][4]

    Example 5.8.3This program checks if a matrix is symmetric or not.# include# includeconst int N = 3;void main( ){

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    75/203

    75

    int i, j;int a[N][N];bool symmetr = true;for ( i=0, i< N, ++i)

    for (j=0, j> a[i][j];

    for ( i=0, i< N, ++i)for (j=0, j

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    76/203

    76

    struct employee{char* firstname;char* lastname;long salary;

    };W her e we d e fin e a structur e in our progra m ???To access the field inside a structure variable, you append a periodto the variable name, followed by the field name using the syntax:

    varia bl e .fi eld ;

    When you use a period to access a structure fields, the period isreferred to as the membe r s el ection op erator . Example 5.9.1# include struct Date // this is a global declaration{

    int month;int day;

    int year;};void main(){

    Date birth;birth.month = 12;

    birth.day = 28;birth.year = 1982;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    77/203

    77

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    78/203

    78

    { 35987, "Ernst, T.", 5.43 },{ 36203, "Gwodz, K.", 8.72 } };

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    79/203

    79

    Chapter 6 MODULARITY USING FUNCTIONS

    6.1 FUNCTION AND PARAMETER DECLARATIONSA function allows you to treat a r elat ed group of C++ statements as

    a single unit. De fining a Functiondata_type name_of_function (parameters){

    statements;}A function definition consists of four parts:

    y A reserved word indicating the return data type of the functionsreturn value.

    y The function namey Any parameters required by the function, contained within

    parentheses.y The functions statements enclosed in curly braces { }.

    void FindMax(int x, int y) /noi dung cua mot ham{

    int maxnum;if ( x > = y)

    maxnum = x;else

    maxnum = y;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    80/203

    80

    You designate a data type for function since it is common to return avalue from a function after it executes. Variable names that will be used in the function header line arecalled for m al para me t ers .(noi dung tham so)

    C all Functions

    To execute a function, you must invoke, or call it from the main () function.The values or variables that you place within the parentheses of afunction call statement //cau lenh// are called arguments or actual

    para me t ers .Example: findMax( firstnum, secnum);

    Function P rototyp es(ha m nguy en)A function prototype d eclar es to the compiler that you intend to usea function later in the program.I f you try to call a function at any point in the program prior to itsfunction prototype or function definition, you will receive an error when you compile the project.Example 6.1.1void FindMax(int, int) ; // the function prototypeint main() //function father {

    function header line

    {named constants;

    variable declarations;any other statements

    }

    Function header

    Function body

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    81/203

    81

    int firstnum, secnum;cout > firstnum;cout > secnum;FindMax(firstnum, secnum); // the function is called herereturn 0;

    }

    P assing b y V alu e y The called function receives a copy of the values stored in the

    actual parametersy Control is transferred to the called function.

    Example: The statement find M a x( firstn u m, secn u m ); calls thefunction find M a x() and causes the values currently residing in thevariables firstn u m and secn u m to be passed to findMax().// ham co 2gia tri can dinh nghia(theo mot bien nao do.example:int

    Functions with E m pty P ara me t er ListsThe function prototype requires either the keyword void or nothingat all between the parentheses following the function name.Example:

    int display(); list in parenthesesint display(void); list:void

    6.2 RETURNING VALUES //dieu chinh tri lai for variable To actually return a value to a variable, you must include the returnstatement within the called function.

    r eturn valu e; or r eturn( valu e );

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    82/203

    82

    R emember that valu es passes back and forth between functions must be of the sa me data typ e.Example 6.2.1# include int FindMax(int, int); // the function prototypeint main(){

    int firstnum, secnum, max;cout > firstnum;cout > secnum;max = FindMax(firstnum, secnum); // the function is called

    herecout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    83/203

    83

    # include double tempvert(double); // function prototypeint main(){

    const CONVERTS = 4; // number of conversions to be madeint count; // start of declarationsdouble fahren;for(count = 1; count fahren;

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    84/203

    84

    # include inline double tempvert(double inTemp) // an inline function{

    return (5.0/9.0) * (inTemp - 32.0);}int main(){

    const CONVERTS = 4; // number of conversions to bemade

    int count; // start of declarationsdouble fahren;

    for(count = 1; count fahren;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    85/203

    85

    void showabs(int x){

    if( x < 0)x = -x;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    86/203

    86

    6.3 VARIABLE SCOPE //tam vuc cua bien Scope refers to wh er e in your program a declared variable or constant is allow ed us ed .

    V aria bl e scop e y G lobal scop e refers to variables declared outside of any

    functions or classes and that are available to all parts of your program.

    y Local scop e refers to a variable declared inside a function andthat is available only within the function in which it is declared.

    Example 6.3.1# include int firstnum; // create a global variable named firstnumvoid valfun(); // function prototype (declaration)int main(){

    int secnum; // create a local variable named secnumfirstnum = 10; // store a value into the global variable

    secnum = 20; // store a value into the local variablecout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    87/203

    87

    {int secnum; // create a second local variable named secnumsecnum = 30 ; // this only affects this local variable's valuecout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    88/203

    88

    {float number = 26.4; // a local variable named number

    //ten bien dia phuongcout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    89/203

    89

    extern float price;extern float yld;

    6.4.1 Local Variable Storage Classes //bien dia Phuong cat giulop

    Local variables can only be members of the auto, static, or register storage classes.I f no class description is included in the declaration statement, thevariable is automatically assigned to the auto class. neu khong co lop

    bao gom cac lenh khai bao thi mac dinh bien tu dong se gan 1 lop.

    A uto m atic V aria bl esy A uto m atic storag e duration refers to variables that exists only

    during the lif eti me of the co mm and block (such as a function)that contains them.

    Example 6.4.1# include void testauto(); // function prototypeint main(){

    int count; // count is a local auto variablefor(count = 1; count

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    90/203

    90

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    91/203

    91

    teststat(); return 0;

    }void teststat(){

    static int num = 0; // num is a local static variablecout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    92/203

    92

    register double difference;

    6.4.2 Global Variable Storage Classes //lop:bien toan cuc y Created by definition statements e xternal to any function. sang

    tao bang cau dinh nghia cau lenhexternaly Exists until the program in which it is declared finishesexecuting.

    y Global variables may be declared as static or e xternal (but not both).

    y The purpose of the e xt ernal storage class is to e xt end th e scop e of a glo bal varia bl e beyond its normal boundaries.

    //file1int price;float yield;static double coupon;..int main(){

    func1():func2():func3():func4():

    }

    int func1();{

    .

    .}

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    93/203

    93

    int func2();{

    .

    .}//end of file1

    //file2double interest;int func3();{

    .

    .}int func4();{

    .

    .}//end of file2

    y A lthough the variable price has been declared in file1 , we wantto use it in file2. Placing the statement e xtern int price in file2,we can extend the scope of the variable price into file2.//khai

    bao bien pricexac dinh tam vuc cua no trong file2 y Now the scope of the variable price is not only in file1 , but also

    in f u nc3 and f u nc4 . bay gio gia tri cua bien khong con o trongfile1ma con trong cac file2.3

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    94/203

    94

    //file1int price; //price : gia trifloat yield; //yield : loi nhuanstatic double coupon; //coupon : phieu (mua hang)..int main(){

    func1():func2():func3():

    func4():}external double interest;int func1();{

    .

    .}int func2();{

    .

    .}//end of file1

    //file2double interest;

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    95/203

    95

    external int price;int func3();{

    .

    .}int func4();{

    extern float yield;..

    }//end of file2 Note:1. We cannot make static variables external.2. The scope of a global static variable cannot extend beyond the

    file in which it is declared. static gia tri tinh khong thay doi.xettrong ham nay thi bien dung cho rat nhieu file khac nhau nenkhong the dat truoc valiable static//no o dang congkhai//xac nhan la toan cuc.

    6.5 PASS BY REFERENCE USING REFERENCEPARAMETERS //tham chieu den 1 tham so da co

    R e f er enc e P ara me t ersy call b y valu e, a copy of the arguments value is made and passed to the called function. Changes to the copy do not effectthe original variables value in the caller.

    y call- b y-r e f er enc e, the caller gives the called function the abilityto access the callers data directly, and to modify that data if thecalled function chooses so.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    96/203

    96

    For example, the declaration int& count in the function h ead er means count is a reference parameter to an int.Example 6.5.1# include void newval(float &, float&); // prototype with tworeferences //kieu mau voi 2 bien tham khaoint main(){

    float firstnum, secnum;cout > firstnum >> secnum;

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    97/203

    97

    The output of the above program:Enter two numbers: 22.5 33.0

    The value in firstnum is: 22.5The value in secnum is: 33

    The value in xnum is: 22.5The value in ynum is: 33

    The value in firstnum is: 89.5

    The value in secnum is: 99.5

    Example 6.5.2# include void calc (float, float, float, float&, float&); // prototypeint main(){

    float firstnum, secnum, thirdnum, sum, product;cout > firstnum >> secnum >> thirdnum;calc(firstnum, secnum, thirdnum, sum, product); / call the

    functioncout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    98/203

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    99/203

    99

    result = factorial(n);cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    100/203

    100

    The activation-record for the first call to factorial().

    The stack for the second call to factorial

    The stack for the third call to factorial()Example 6.6.2

    1

    reserved for returnvalue

    return address

    2

    reserved for returnvalue

    return address

    3

    reverved for returnvalue

    return address

    2

    reserved forreturn value

    return address

    3

    reserved forreturn value

    return address

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    101/203

    101

    Fibonacci numbers:

    F N = F N-1 + F N-2 for Nu 2F0 = F 1 = 1

    # includeint fibonacci(int);void main(){

    int m;cout m;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    102/203

    102

    modify A rray( hourly Temperature , size);//modify thay doiham,bo sung ham.

    passes the array ho u rlyTemperat u re and its size to functionmodify A rray .

    void modifyArray(int b[], int arraySize)

    Example 6.7.1To illustrate the use of array and function, we set for ourselves thefollowing tasks:

    1. R ead in the amount to be deposited in the bank, the interest rateand the number of years to deposit.

    2. I nvoke the function to compute a table which keeps the amountwe get after i years of deposit at the i-th component of the array.

    3. Display out the above array/* Compute compound interest */# include# include# define YMAX 50void interest(double, double, int, double []);void main(){

    double deposit, rate;int i, years;

    double compounded[YMAX];cout>deposit>>rate>>years;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    103/203

    103

    or equal

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    104/203

    104

    a[x] = 2*x;cout searchKey;element = linearSearch(a, searchKey, arraySize);if(element !=-1)

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    105/203

    105

    dou ble dPrimeInterest ;

    dou ble * pPrimeInterest ;

    pPrimeInterest = & dPrimeInterest ; y To access or modify the contents of the variable pointer to by

    the pointer, you precede a pointer name in an expression withthe de-reference (*) operator .

    Example 6.8.1The program in this example demonstrates the pointer operators.Memory locations are output in this example as hexadecimalintegers.

    # includevoid main(){

    int a;int *aPtr; // aPtr is a pointer to an integer a = 7;

    aPtr = &a; //aPtr set to address of acout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    106/203

    106

    The value of a is 7The value of *aPtr is 7

    6.8.1 Pointers and Arrays Notice that the name of an array by itself is equivalent to the bas e addr ess of that array. that is, the name z in isolation is eq u ivalent tothe e x pression & z[0] .Example 6.8.2a# includevoid main(){ int z[] = { 1, 2, 3, 4, 5};

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    107/203

    107

    The following program displays all elements in an array. I t uses pointer and offset to access to each element in the array.

    # include int main(){

    const int ARRAYSIZE = 5;int *gPtr; // declare a pointer to an int

    int i, grade[ARRAYSIZE] = {98, 87, 92, 79, 85};gPtr = &grade[0];

    // store the starting array addressfor (i = 0; i < ARRAYSIZE; i++)

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    108/203

    108

    6.8.2 Pointers and StringsWe can scan through a string by using pointer.

    /* Printing a string one character at a time using a non-constant pointer to constant data */# includevoid main( ){

    char string[] = Adams;char *sPtr;

    sPtr = &string[0];cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    109/203

    109

    struct Employee // declare a global type{

    int idNum;double payRate;double hours;

    };double calcNet(Employee); // function prototypeint main(){

    Employee emp = {6782, 8.93, 40.5};double netPay;

    netPay = calcNet(emp); // pass by valuecout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    110/203

    110

    y An alternative to the pass-by-value function call, we can pass astructure by passing a pointer . The following example showshow to pass a structure by passing a pointer.

    # include struct Employee // declare a global type{

    int idNum;double payRate;double hours;

    };double calcNet(Employee *); //function prototypeint main(){

    Employee emp = {6782, 8.93, 40.5};double netPay;

    netPay = calcNet(&emp); // pass an addresscout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    111/203

    111

    The net pay for employee 6782 is $361.665

    y Is th er e any oth er solutions???

    6.10 THE typedef DECLARATION STATEMENT

    Construct alternate names for an existing C++ data type name.typed e f data-typ e new-typ e-na me

    Example:typedef float REAL;REAL val; float val;

    Example:typedef double* DPTR;DPTR pointer1; double* pointer1;

    Example:typedef struct{

    char name[20];int idNum;

    } EMPREC;The declaration

    EMPREC employee[75];is equivalent to

    struct{

    char name[20];int idNum;

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    112/203

    112

    } employee[75];

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    113/203

    113

    Chapter 7 INTRODUCTION TO CLASSES

    7.1 STACK VERSUS HEAP //ngan truy cap den 1 vung du lieuma minh da gioi han

    y A stack is a region of memory where applications can store datasuch as local variables, function calls, and parameter information. //ngan xep la mot mien cua bon ho noi ma ungdung co the cat giu du lieu nhu la mot bien dia Phuong, goiham,thong tin tham so.

    y The programmers have no control over the stack. C++automatically handles placing and removing data to and from

    stack.y The heap or free store, is an area of memory that is available to

    application for storing data whose existence and size are notknown until run-time.

    Th e new K e yword The new keyword creates a variable on the heap and returns a

    pointer to the variables heap address. //tu khoa NEW tao ra 1 bientrong 1 vung du lieu nao do.sau do con tro se tra 1 bien trong vungdu lieu theo mot dia chi da xac dinh.

    new type_name ;

    Example:int * pPointer;

    pPointer = new int; Th e d el et e K e yword

    You use the delete keyword to de-allocate memory that has beenreserved on the heap.

    delete pointer_name ;

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    114/203

    114

    delete pPointer;int *arrayPtr = new int[10];delete [] arrayPtr;

    Notice that the delete keyword does not delete the pointer itself. R ather, it deletes the contents of the heap memory address pointed to

    by a pointer variable. You can reuse(dung lai) the pointer itself after calling the delete keyword. The pointer still exists and points tothe same heap memory address that it did before calling the delete

    keyword.Example 7.1.1# includevoid main( ){

    double* pPrimeInterest = new double;

    *pPrimeInterest = 0.065;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    115/203

    115

    }The output of the above program:The value of pPrimeInterest is: 0.065The memory address of pPrimeInterest is: 0x0066FD74

    The value of pPrimeInterest is: 0.070The memory address of pPrimeInterest is: 0x0066FD74. Note: The above program declares the pPrimeInterest pointer on the

    heap and assign to it a value of 0.065. Then the delete keyworddeletes the heap address that stores the value of 0.065. Finally, anew value is added to the heap address. You can see that after the delete statement executes, the pPimeInterest pointer still

    point to the same memory address.Example 7.1.2:The following program allocates contiguous memory for an array of integers using the new operator and the object of the array isdestroyed by the delete operator. The program reads a set of numbers from keyboard and displays it on the screen.

    # include void main( ){

    int *ptr_a = new int[20];int *ptr_n = new int;int i;cout > *ptr_n;for (i = 0; i ptr_a[i];

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    116/203

    116

    }cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    117/203

    117

    y Classes are referred to as us er-d e fin ed data typ es or programmer-defined data types because you can work with aclass as a single unit, or objects, in the same way you work withvariables.

    y When you declare an object from a class, you are said to be

    instantiating an object.y The most important feature of C++ programming is class

    definition with the class keyword. You define classes the sameway you define structures, and you access a classs datamembers using the member selection operator .

    Example:

    class Stocks //ton tai dau; sau khi ket thuc class{public:

    int iNumShares;double dPurchasePricePerShare;

    double dCurrentPricePerShare;}; void main( ){

    Stocks stockValue;stockValue.iNumShares = 500;stockValue.dPurchasePricePerShare = 10.785;

    stockValue.dCurrentPricePerShar = 6.5;}

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    118/203

    118

    P oint ers and R e f er enc es to Obje ctsy When declaring and using pointers and references to class

    objects, follow the same rules as you would when declaring andusing pointers and references to structures.

    y You use the indirect member selection operator (->) to accessclass members through a pointer to an object either on stack or on the heap.

    Example 7.2.1//stock : kho chua cac du lieu lien quan den ham# includeclass Stocks{public:

    int iNumShares;

    double dPurchasePricePerShare;double dCurrentPricePerShare;

    };double totalValue(Stocks* pCurStock);void main( ){

    //allocated on the stack//with a pointer to the stack objectStocks stockPick;Stocks* pStackStock = &stockPick;pStackStock->iNumShares = 500;

    pStackStock-> dPurchasePricePerShare = 10.785;pStackStock-> dCurrentPricePerShare = 6.5;cout dPurchasePricePerShare = 32.5;pHeapStock-> dCurrentPricePerShare = 48.25;cout iNumShares;return dTotalValue;

    }

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    119/203

    119

    Output of the above program:32509650 Note: The totalVal u e() function is not a function member of theStocks class. R ather, it is a function that is available to the entire

    program.7.3 INFORMATION HIDING

    y The principle of information hiding states that any classmembers that other programmers , or clients, do not need toaccess or know about should be hidden.

    y Many programmers prefer to make all of their data member

    private in order to prevent clients from accidentally assigning the wrong value to a variable or from viewing the internalworkings of their programs.

    7.3.1 Access SpecifiersAccess specifiers control a clients access to data members andmember functions. There are four levels of access specifiers: public,

    private, protected, and friend.y The public access specifier allows anyone to call a classs

    function member or to modify a data member.y The private access specifier is one of the key elements in

    formation hiding since it prevents clients from calling member functions or accessing data members.

    y Both public and private specifiers have what is called classscope : class members of both access types are accessible by anyof a classs member functions.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    120/203

    120

    Example 1:class Stocks {public:

    int iNumShares;double dPurchasePricePerShare;

    private:double dCurrentPricePerShare;

    };

    Example 2:

    class Times {public:Times();void setTime( int, int, int );void printMilitary();void printStandard();

    private:int hour;int minute;int second;

    };

    Stocks

    i NumSharesdPurchasePricePer SharedCurrentPricePer Share

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    121/203

    121

    y The d e fault acc ess specifier for classes is pri vat e.

    7.3.2 Interface and Implementation FilesThe separation of classes into separate interface and implementationfiles is considered to be a f u ndamental software de velopment techniq u e since it allows you to hide the details of how your classesare written and makes it easier to modify programs.

    y The interface code refers to the data member and functionmember declarations inside a classs braces.

    y The implementation code refers to a classs functiondefinitions and any code that assigns values to a classs datamembers.

    P r eve nting M ultipl e Inclusion

    With large program, you need to ensure that you do not include

    multiple instances of the same header file.C++ generates an error if you attempt to compile a program thatincludes multiple instances of the same header file. To prevent thiskind of error, most C++ programmers use the # define preprocessor directive with the # if and # endif preprocessor directives in header files.

    Times

    hour minute

    second

    setT ime() printMilitary pring Standard()

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    122/203

    122

    The # if and # endif preprocessor directives determine which portionsof a file to compile depending on the result of a conditionalexpression.The syntax for the # if and # endif preprocessor directives:

    # if conditional e

    x pression statements to compile ;

    # endif Example:# if !defined(STOCKS_H)# define STOCKS_Hclass Stocks {private:

    int iNumShares;double dPurchasePricePerShare;double dCurrentPricePerShare;

    };# endif Note: Common pratice when defining a header files constant is touse the header files name in uppercase letters appended with H. For example, the constant for the stocks.h header is usually defined asSTO CK S _H.

    7.4 MEMBER FUNCTIONSA lthough member functions are usually defined in animplementation file, they can also be defined in an interface file.Functions defined inside the class body in an interface file are calledinline functions .Example:class Stocks {

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    123/203

    123

    public:double getTotalValue(int iShares, double dCurPrice){

    double dCurrentValue;iNumShares = iShares;dCurrentPricePerShare = dCurPrice;dCurrentValue = iNumShares*dCurrentPricePerShare;return dCurrentValue;

    }private:

    int iNumShares;double dPurchasePricePerShare;

    double dCurrentPricePerShare;};

    Example 7.4.1//stocks.hclass Stocks{public:

    double getTotalValue(int iShares, double dCurPrice);private:

    Stocks

    i N

    umS

    haresdPurchasePricePer SharedCurrentPricePer Share

    getTotalValue()

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    124/203

    124

    int iNumShares;double dPurchasePricePerShare;double dCurrentPricePerShare;

    };# endif

    // stocks.cpp# include stocks.h# include

    double Stocks::getTotalValue(int iShares, double dCurPrice){

    double dCurrentValue;iNumShares = iShares;dCurrentPricePerShare = dCurPrice;dCurrentValue = iNumShares*dCurrentPricePerShare;return dCurrentValue;

    }void main(){

    Stocks stockPick;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    125/203

    125

    {function body

    }Example 7.4.2// time1.h# if !defined(TIME1_H)# define TIME1_Hclass Time {public:

    Time(); // constructor void setTime( int, int, int ); // set hour, minute, secondvoid printMilitary(); // print military time formatvoid printStandard(); // print standard time format

    private:int hour;int minute;int second;

    };// Time1.cpp# include time1.h# include

    // Time constructor initializes each data member to zero.

    // Ensures all Time objects start in a consistent state.Time::Time() {hour = minute = second = 0;}

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    126/203

    126

    void Time::setTime( int h, int m, int s ){

    hour = ( h >= 0 && h < 24 ) ? h : 0;minute = ( m >= 0 && m < 60 ) ? m : 0;second = ( s >= 0 && s < 60 ) ? s : 0;

    }

    void Time::printMilitary(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    127/203

    127

    t.setTime( 13, 27, 6 );cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    128/203

    128

    C onstructor Functionsy A constructor function is a special function with the same

    name as its class. This function is called automatically when anobject from a class is instantiated.

    y You define and declare constructor functions the same way youdefine other functions, although you do not include a returntype since constructor functions do not return values.

    Example:

    class Payroll{public:

    Payroll( ){ // constructor functiondFedTax = 0.28;dStateTax = 0.05;

    };private:

    double dFedTax;double dStateTax;

    }y You also include just a function prototype in the interface file

    for the constructor function and then create the functiondefinition in the implementation file.

    Payroll::Payroll( ){ // constructor functiondFedTax = 0.28;dStateTax = 0.05;

    };Example 7.4.3# include

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    129/203

    129

    # include

    // class declaration sectionclass Date{

    private:int month;int day;int year;

    public:Date(int = 7, int = 4, int = 2001); // constructor with default

    values};

    // implementation sectionDate::Date(int mm, int dd, int yyyy){

    month = mm;day = dd;year = yyyy;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    130/203

    130

    return 0;}The output of the above program:Created a new data object with data values 7, 4, 2001Created a new data object with data values 7, 4, 2001Created a new data object with data values 4,1, 2001

    y De fault constructor refers to any constructor that does notrequire any parameters when it is called.

    For example in Example 7.4.3, the prototype Date ( int = 7, int = 4,int = 2001 ) is valid for a default constructor. Here, each argumenthas been given a default value. Then an object can be declared astype Date without supplying any further arguments.

    A ssign me nts

    1. R ead the following program for understanding. Then edit it as one program file and run it on V isual C++ environment.# includeclass student{private:

    long int rollno;int age;char sex;float height;

    float weight;public:

    void getinfo();void disinfo();

    };

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    131/203

    131

    void student::getinfo(){

    cout > rollno;cout > age;cout > sex;cout > height;cout > weight;}void student::disinfo(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    132/203

    132

    }Then organize the program into one interface file and oneimplementation file and run them again.2. R ead the following program that reads the students informationfrom the keyboard and displays the contents of the whole class onthe screen//assign4_2.cpp# includeconst int MAX = 100class student{private:

    long int rollno;int age;char sex;float height;float weight;

    public:

    void getinfo();void disinfo();};void student::getinfo(){

    cout > rollno;cout > age;cout > sex;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    133/203

    133

    cin >> height;cout > weight;

    }void student::disinfo(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    134/203

    134

    I mplement the above program on V isual C++ environment.3. The following program simulates a simple banking system inwhich the initial balance and the rate of interest are read from thekeyboard and these values are initialized using the constructor function. The program consists of the following methods:

    y to initialize the balance amount and the rate of interesty to make a deposity to withdraw an amount from the balancey to find the compound interest based on the rate of interesty to know the balance amounty to display the menu options//demonstration of constructor

    //simulation of simple banking system# include# includeclass account{private:

    float balance;float rate;

    public:account(); //constructor void deposit();void withdraw();void compound();void getbalance();void menu();

    };account::acount()

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    135/203

    135

    {cout> balance;cout> rate;

    }//depositvoid account:: deposit(){

    float amount;cout amount;

    balance = balance + amount;}void account::withdraw(){

    float amount;cout amount;

    if(amount

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    136/203

    136

    balance = balance + interest;cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    137/203

    137

    break;case 'd':

    acct.compound();break;

    case 'd':acct.getbalance();break;}

    }}I mplement the above program on V isual C++ environment.

    4. The following program solves a quadratic equation using anobject-oriented programming technique in which the member functions are defined as an inline substitution.

    (chuong trinh bac hai sau day se lam sang to ,su dung viec dinhhuong doi tuong trong chuong trinh bang thu thuat ma so hamdinh nghia ro tinh chat nhu mot su thay the ben trong)

    #include# include

    class equation{private:

    float a;float b;float c;

    public:void getinfo(float a, float b, float c);void display( );void equal(float a, float b);void imag( );

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    138/203

    138

    void real(float a, float b, float det);}; // end of class declaration section// beginning of implementation sectionvoid equation::getinfo(float aa, float bb, float cc){

    a = aa; b = bb; c = cc;}void equation::display( ){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    139/203

    139

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    140/203

    140

    Note: I n the above program, the class declaration section and classimplementation section are included in the same source file (.cppfile).5. Construct a class name S t u dent consisting of an integer studentidenfification number, an array of five floating point grades, and an

    integer representing the total number of grades entered. Theconstructor for this class should initialize all S tudent data membersto zero. I ncluded in the class should be member functions to

    - enter a student I D number,- enter a single test grade and update the total number of grades

    entered, and- compute an average grade and display the student I D following

    by the average grade.I nclude the class S t u dent within a complete program. The programshould declare two objects of type Student and accept and displaydata for the two objects to verify operation fo the member functions.6. Construct a class named Rectangle that has floating-point datamembers name length and width . The class should have a

    constructor that sets each data member to 0, member functionsnamed perimeter () and area () to calculate the perimeter and area of a rectangle, respectively, a member function named getdata () to seta rectangles length and width, and a member function named

    showdata () that display a rectangles length, width, perimeter, andarea.I nclude the Rectangle class within a working C++ program.

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    141/203

    141

    Chapter 8 OBJECT MANIPULATION

    8.1 ADVANCED CONSTRUCTORS// xay dung dang cao cap I n the last chapter, we already notice that constructors can provide a

    mechanism for initializing data members. However, constructors cando more than initializing data members. They can execute member functions and perform other type of initialization routines that aclass may require when it first starts.

    8.1.1 Parameterized Constructorsy A lthough constructor functions do not return values, they can

    accept parameters that a client can use to pass initializationvalues to the class.

    y Once you create a parameterized constructor, you have tosupply parameters when you instantiate a new object.

    //Payroll.hclass Payroll{public:

    Payroll(double, double);private:

    double dFedTax;double dStateTax;

    }

    //Payroll.cpp# include Payroll.h

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    142/203

    142

    # include Payroll::Payroll(double dFred, double dState){

    dFedTax = dFed;dStateTax = dState;

    };void main( ){

    Payroll employee; //illegal

    }y Constructor functions can be overloaded , just like other

    functions. This means that you can instantiate different versions

    of a class, depending on the suplied parametersy Being able to overload a constructor function allows you to

    instantiate an object in multiple ways.//Payroll.hclass Payroll{public:

    Payroll();Payroll(double dFed);Payroll(double dFed, double dState);

    private:double dFedTax;double dStateTax;

    }

    //Payroll.cpp# include Payroll.h# include

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    143/203

    143

    Payroll::Payroll(){dFedTax = 0.28;dStateTax = 0.05;

    };Payroll::Payroll(double dFed){

    dFedTax = dFed;};

    Payroll::Payroll(double dFred, double dState){dFedTax = dFed;dStateTax = dState;

    };void main( ){

    Payroll employeeFL(0.28);Payroll employeeMA(0.28, 0.0595);

    }Example 8.1.1

    The program in this example finds the distance between two pointsusing the pointer to class objects technique.//points#include < ios tream.h>#includecla ss p oi nt {pr ivate:

    int x,y;

    publ ic:p oi nt( int xnew, int ynew);inl ine int getx(){

    return(x);}

    inl ine int gety(){

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    144/203

    144

    return(y);}

    d o uble f indd is t(p oi nt a, p oi nt b);};p oi nt::p oi nt( int xnew, int ynew) //parameter ized c o n s truct o r {

    x = xnew;y = ynew;

    }d o uble p oi nt::f indd is t(p oi nt a, p oi nt b){

    d o uble temp;temp = ((b.y a.y)*(b.y a.y) + (b.x a.x)*(b.x a.x));return ( sq rt(temp));

    }voi d ma in(){

    d o uble value;p oi nt a o bj(4,3), b o bj(0,-1); //h ien th i g ia tr i d iem 1(4,3); d iem 2 (0, -1)p oi nt *aptr = &a o bj;p oi nt *bptr = &b o bj;aptr->get(x);aptr->get(y);bptr->get(x);bptr->get(y);value = aptr->f indd is t(a o bj, b o bj);c o ut

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    145/203

    145

    Payroll::Payroll(double dFed, double dState){dFedTax = dFed;dStateTax = dState;

    };You can use initialization list to rewrite the above constructor function. //ban co the khoi tao danh sach de ghi chen len cac hamdang xay dung.cau truc co dang duoi day.Payroll::Payroll(double dFed, double dState)

    :dFedTax(dFed), dStateTax(dState){};

    8.1.3 Parameterized Constructors that Uses DefaultArguments //xay dung tham so va doi so mac dinh

    y To create a parameterized constructor that uses defaultarguments, we can put the default values at the constructor

    prototype.Example 8.1.2

    # includeclass Employee{private:

    int idNum;double hourlyRate;

    public:

    Employee(const int id = 9999, const double hourly =5.65);void setValues(const int id, const double hourly);void displayValues();

    };

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    146/203

    146

    Employee::Employee(const int id, const double hourly){

    idNum = id;hourlyRate = hourly;

    }void Employee::displayValues(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    147/203

    147

    8.1.4 Copy ConstructorsThere are two ways to create a new object from an existing object.You can use either the syntax:

    class new_object = e xisting_object ;

    or the syntax:class new_object ( old_object );

    y R egardless of which syntax you use to copy an object, itsimportant to know that no defa u lt constr u ctor e xec u tes for making the new object . I nstead, C++ uses a copy constructor toexactly copy each of the first objects data members into thesecond objects data members in an operation known as

    memberwise copying .y A copy constructor is a special constructor that is called when

    a new object is instantiated from an old object.y C++ supplies a default copy constructor that automatically

    copies the members of the original object to the new object.y I n some situations, you must write your own copy constructor

    instead of using default copy constructor.y Copy constructors are identical to standard constructors, exceptthey must accept a single call-by-reference parameter to anobject preceded by the const keyword to indicate that theoriginal object is not to be modified in any way.class_name ( const class_name & object_name );

    y The call-by-reference object parameter in the copy constructor represents the object being copied.

    Example 8.1.3The following code is an example of a copy constructor function for the Stocks class that dynamically allocate a new memory for the

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    148/203

    148

    stock name for any new S tocks objects created by copying anexisting object.//Stocks.hclass Stocks {public:

    Stocks(char* szName);Stocks(const Stocks&); //copy constructor

    void setStockName(char* szName);char* getStockName();void setNumShares(int);int getNumShares(int);

    void setPricePerShare(double);double getPricePerShar();double calcTotalValue();

    private:char* szStockName;int iNumShares;

    double dCurrentValue;double dPricePerShare;};//Stocks.cpp# include stocks.h# include #

    include Stocks::Stocks(char* szName){szStockName = new char[25];strcpy(szStockName, szName);

    };

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    149/203

    149

    Stocks::Stocks(const Stocks& sourceStock){szStockName = new char[25];strcpy(szStockName, sourceStock.szStockName);

    };void Stocks::setNumShares(int iShares){

    iNumShares = iShares;}int Stocks::getNumShares(){

    return iNumShares;}void Stocks::setPricePerShare(double dPrice){

    dPricePerShare = dPrice;}int Stocks::getPricePerShare(){

    return dPricePerShare;}void Stocks::setStockName(char* szName){

    strcpy(szStockName, szName);}char* Stock::getStockName(){

    return szStockName;}double Stocks::calcTotalValue(){

    dCurrentValue = iNumShares*dPricePerShare;return dCurrentValue;

    }void main(){

    Stocks stockPick1(Cisco);stockPick1.setNumShares(100);

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    150/203

    150

    stockPick1.setPricePerShare(68.875);/* The following statement creates a new object by

    copying anexisting object */

    St o ck s s to ckP ick2( s to ckP ick1);

    stockPick2.setStockName(Lucent);stockPick2.setNumShares(200);stockPick2.setPricePerShare(59.5);cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    151/203

    151

    y A destructor is called in two ways:o when a stack object loses scope when the function in

    which it is declared ends.o when a heap object is destroyed with the delete operator.

    Example 8.2.1//Stocks_02.hclass Stocks {public:

    Stocks(char* szName);Stocks(const Stocks&); //copy constructor ~ St o ck s (); //destructor

    void setStockName(char* szName);char* getStockName();void setNumShares(int);int getNumShares(int);void setPricePerShare(double);double getPricePerShar();

    double calcTotalValue();private:

    char* szStockName;int iNumShares;double dCurrentValue;double dPricePerShare;

    };

    //Stocks.cpp# include stocks_02.h# include

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    152/203

    152

    # include Stocks::Stocks(char* szName){

    szStockName = new char[25];strcpy(szStockName, szName);

    };Stocks::Stocks(const Stocks& sourceStock){

    szStockName = new char[25];strcpy(szStockName, sourceStock.szStockName);

    };Stocks::~Stocks(){

    delete [] szStockName;

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    153/203

    153

    return szStockName;}double Stocks::calcTotalValue(){

    dCurrentValue = iNumShares*dPricePerShare;return dCurrentValue;

    }void main(){

    Stocks stockPick1(Cisco);stockPick1.setNumShares(100);stockPick1.setPricePerShare(68.875);Stocks* stockPick2 = new Stocks(Lucent); //heap

    objectstockPick2->setNumShares(200);stockPick2->setPricePerShare(59.5);cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    154/203

    154

    y Notice that in the above program, the destructor function iscalled only once. The stockPick1 object calls the destructor when it is destroyed by the main () function going out of scope.The stockPick 2 object does not call the destructor since it isdeclared on the heap and must be deleted manually.

    y To delete the stockPick 2 object manually, add the statementdelete stockPick2; to the main () function as in the following program:

    void main(){Stocks stockPick1(Cisco);stockPick1.setNumShares(100);stockPick1.setPricePerShare(68.875);Stocks* stockPick2 = new Stocks(Lucent); //heap

    objectstockPick2->setNumShares(200);stockPick2->setPricePerShare(59.5);cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    155/203

    155

    Destructor called.Destructor called.

    8.3 ASSIGNMENT How assignment works when it is applied to objects???

    Example 8.3.1# include # include

    // class declaration

    class Date{private:

    int month;int day;int year;

    public:Date(int = 7, int = 4, int = 2001); // constructor prototype

    with defaultsvoid showdate(); // member function to display a Date

    };

    // implementation section

    Date::Date(int mm, int dd, int yyyy){

    month = mm;day = dd;

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    156/203

    156

    year = yyyy;}

    void Date::showdate(){

    cout

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    157/203

    157

    y The type of assignment is called memberwise assignment .y I f the class does not contain any pointer data members , this

    defa u lt assignment operator is adequate and can be used.

    A ssign me nt O peratorsy A

    ssignment operators , like all class members, are declared inthe class declaration section and defined in the classimplementation section.void operator= ( ClassName & );

    y The keyword void indicates that the assignment function returnsno value, operator= indicates that we are overloading theassignment operator with our own version.

    y The class name and & within the parentheses indicate that the parameter to the operator is a class reference.

    Example 8.3.2# include # include

    // class declaration

    class Date{

    private:int month;

    int day;int year;

    public:Date(int = 7, int = 4, int = 2001); // constructor prototype

    with defaults

  • 8/8/2019 Slide Ki Thuat Lap Trinh

    158/203

    158

    void operator=(Date&); // define assignment of a datevoid showdate(); // member function to display a date

    };

    // implementation section

    Date::Date(int mm, int dd, int yyyy){

    month = mm;day = dd;year = yyyy;

    }

    void Date::operator=(Date& newdate){

    day = newdate.day; // assign the daymonth = newdate.month; // assign the monthyear = newdate.year; // assign the year return;

    }

    void Date::showdate(){

    cout

  • 8