Top Banner

of 77

Chuong VIII Da Nang Hoa Toan Tu

Apr 03, 2018

Download

Documents

tuantranbk
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    1/77

    1

    Operator Overloading

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    2/77

    2

    8.1 Introduction

    Thao tc trn cc i tng ca lp c thc hin bi gicc thng ip ti cc i tng.

    K php gi hm ny cng knh, c bit l cc lp ton hc.Nn s dng tp cc ton t c sn ca C++ ch r ccthao tc ca i tng => gi l a nng ha ton t

    (operator overloading). Ton t > cng c a nng ha. : ton t trch dng(stream-extraction) v ton t dch chuyn phi.

    C++ cho php a nng ha hu ht cc ton t . Trnh bindch pht sinh on m thch hp da trn kiu m trong ton t c s dng. Mt vi ton t c a nng hathng xuyn, c bit l ton t gn v cc ton t s hcnh + v -.

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    3/77

    3

    8.2 CC NGUYN TC C BN CA A NNG HA TON T

    C th s dng cc kiu c sn v c th nh ngha cc kiu mi. Cckiu c th c s dng vi tp cc ton t phong ph.

    C th s dng cc ton t vi cc kiu do ngi dng nh ngha.C++ khng cho php tocc ton t mi, nhng cho php a nng hacc ton t tn ti khi s dng vi cc i tng ca lp, chngc ngha thch hp vicc kiu mi =>im mnh ca C++.

    Cc ton t c a nng ha bng cch vit mt nh ngha hm nh

    khi chng ta vit mt hm bnh thng, ngoi tr tn hm l t khaoperatortheo sau bi k hiu ca ton t c a nng ha. Prototypeca n c dng nh sau:

    typeoperator operator_symbol ( parameter_list); s dng mt ton t cho cc i tng ca lp, ton t phi c

    a nng ha ngoi tr hai iu. Ton t gn c th s dng vi mi lp m khng cn a nng ha. Ton t a ch (&) cng c th c s dng vi cc i tng

    ca bt k lp no m khng cn a nng ha;

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    4/77

    4

    8.3 CC GII HN CA A NNG HA TON T

    Phn ln cc ton t ca C++ c th c anng ha.

    + - * / % ^ & |

    ~ ! = += -= *=

    /= %= ^= &= |= >>=

    [] () new delete

    Cc ton t khng th a nng ha

    . .* :: ?: sizeof

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    5/77

    5

    Ton t ngoc trn () l ton t gi hm. Sau tn hm c th chanhiu tham s => ton t nhiu ngi.

    Th t u tin ca mt ton t khng th c thay i bi a nngha.

    Tnh kt hp ca mt ton t khng th c thay i bi a nngha.

    Khng th thay i s cc ton hng m mt ton t yu cu: a nngha cc ton t mt ngi vn l cc ton t mt ngi..

    Ton t ba ngi duy nht (?:) ca C++ khng th a nng ha. Cc

    ton t &, *, + vmi ton t c cc phin bn mt v hai ngi.;Cc phin bn mt v hai ngi ny c th c a nng ha ring bit. Vic a nng ha ton t ch lm vic vi cc i tng ca cc kiu

    do ngi dng nh ngha hoc vi mt s pha trn ca mt i tngca kiu do ngi dng nh ngha v mt i tng ca mt kiu csn.

    a nng ha mt ton t gn v mt ton t cng cho php cclnh nh l: object2 = object2 + object1 khng bao hm ton t+= cng c a nng ha php cc lnh nh l: object2 +=object1

    _=>Cn a nng ha r rng ton t += cho lp .

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    6/77

    6

    8.4 HM TON T L CC THNH VIN CA LPHOC KHNG L CC THNH VIN

    Hm ton t c th l hm thnh vin hoc khng thnh vin; hm khngthnh vin thng l friend. Cc hm thnh vin s dng ngm con trthis cha mt trong cc tham s i tng lp ca chng. Tham s lp phi c lit k mt cch tng minh trong li gi hm khng thnhvin.

    Khi a nng ha (), [], -> hoc =,hm a nng ha ton tphi c khaibo nh mt thnh vin lp. i vi cc ton t khc, cc hm a nng ha

    ton t c th l cc hm khng thnh vin (thng l Friend). D ton t c ci t nh th no, ton t vn c s dng cng cchtrong biu thc. Vy cch ci t no tt nht?

    Khi c ci t nh mt hm thnh vin, ton hng cc tri phi l mti tng lp ca ton t. Nu ton hng bn tri phi l mt i tng calp khc hoc mt kiu c snth hm ton t nyphi c ci t nhhm khng thnh vin. Mt hm ton t ci t nh hm khng thnh vincn l mt friendnu hm phi truy cp n cc thnh vin private hocprotected.

    Cc hm thnh vin ch c gi khi ton hng tri ca mt ton t haingi l mt i tng c th ca lp , hoc khi ton hng n ca mt

    ton t mt ngi l mt i tng ca lp .

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    7/77

    7

    V d :xy dng lp s phc vi tn lp lComplexv a nng ha ton t +

    #include

    class Complex {private: double R, I;

    public: Complex(double R=0.0,double I=0.0);// Constructor mc nhvoid Print(); // Hin th s phcComplex operator+(Complex Z); // Php cng gia hai s phc

    Complex operator+(double R); // Php cng mt s phc vi mt s thc};

    Complex::Complex(double T,double A) {

    R = T; I = A; }

    void Complex::Print() {

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    8/77

    8

    Complex Complex::operator + (double T) {

    Complex Tmp;

    Tmp.R = R + T;

    Tmp.I = I;return Tmp; }

    int main() {

    Complex X,Y(4.3,8.2),Z(3.3,1.1);

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    9/77

    9

    Do a nng ha ton t + trn lp Complex v d trn, chng ta c th vit:X = Y + Z;

    Cu lnh ny c trnh bin dch hiu:X = Y.operator + (Z);

    Nh vy, trong biu thc Y + Zi tng bn tri ton t + (l i tng Y)l i tng m qua , hm thnh vin ton t operator + ()c gi. Do hm thnh vin ton t + ch nhn mt tham s l i tng bn phiton t v i tng bn tri ton t l i tng to li gi cho hm ton tv c truyn bi con tr this.

    Hm operator + () tr v mt i tng Complex. Do vy chng ta c thvit:(Y + Z).Print();

    in trn mn hnh s phc ca i tng c tr v. i tng do Y + Zsinh ra nh vy l mt i tng tm thi. N s khng tn ti khi hm

    thnhPrint() kt thc. Ton t +cho php mt chui php cng. Nn chng ta cng c th vit:X = X + Y + Z;

    Tuy nhin chng ta khng th no vit c cu lnh sau:X = 3.5 + Y; // Li !!! Lam the nao ?

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    10/77

    10

    cch a nng ha ton t

    Biu thc Hm thnh vin Hm khng thnh vina#b a.operator#(b) operator#(a,b)

    #a a.operator#() operator#(a)

    a=b a.operator=(b)

    a[b] a.operator[](b)

    a(b) a.operator()(b)

    a-> a.operator->()

    a++ a.operator++(0) operator++(a,0)a-- a.operator--(0) operator--(a,0)

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    11/77

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    12/77

    12V d : xy dng lp Complexv a nng ha ccton t + - += -= v == != > >= <

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    13/77

    13

    // Cc ton t so snhint operator == (Complex Z);

    int operator != (Complex Z);

    int operator > (Complex Z);

    int operator >= (Complex Z);

    int operator < (Complex Z);

    int operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    14/77

    14

    Complex::Complex() {

    R = 0.0;

    I = 0.0; }

    Complex::Complex(double T,double A) {

    R = T;

    I = A;}

    Complex::Complex(const Complex & Z) {

    R = Z.R;

    I = Z.I; }

    Complex::Complex(double T) {

    R = T;

    I = 0.0; }

    void Complex::Print() {

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    15/77

    15

    Complex Complex::operator + (Complex Z) {

    Complex Tmp;

    Tmp.R = R + Z.R;

    Tmp.I = I + Z.I;return Tmp; }

    Complex Complex::operator - (Complex Z) {

    Complex Tmp;

    Tmp.R = R - Z.R;

    Tmp.I = I - Z.I;

    return Tmp; }

    Complex Complex::operator += (Complex Z) {

    R += Z.R;

    I += Z.I;return *this; }

    Complex Complex::operator -= (Complex Z) {

    R -= Z.R;

    I -= Z.I;

    return *this; }

    16

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    16/77

    16

    int Complex::operator == (Complex Z) {

    return (R == Z.R) && (I == Z.I); }

    int Complex::operator != (Complex Z) {

    return (R != Z.R) || (I != Z.I); }

    int Complex::operator > (Complex Z) {

    return Abs() > Z.Abs(); }

    int Complex::operator >= (Complex Z) {return Abs() >= Z.Abs(); }

    int Complex::operator < (Complex Z) {

    return Abs() < Z.Abs(); }

    int Complex::operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    17/77

    17

    int main() {

    Complex X, Y(4.3,8.2), Z(3.3,1.1), T;

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    18/77

    18cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    19/77

    19

    20

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    20/77

    20

    Dng cc hm ton t +, - v cc hm tont so snh l hm khng thnh vin.

    class Complex {

    private: double Real,Imaginary;public: Complex(); // Constructor mc nh

    Complex(double R,double I);

    Complex (const Complex & Z); // Constructor sao chp

    Complex (double R); // Constructor chuyn i

    void Print(); // Hin th s phcfriend Complex operator + (Complex Z1,Complex Z2);friend Complex operator - (Complex Z1,Complex Z2);

    Complex operator += (Complex Z);

    Complex operator -= (Complex Z);

    friend int operator == (Complex Z1,Complex Z2);friend int operator != (Complex Z1,Complex Z2);

    friend int operator > (Complex Z1,Complex Z2);

    friend int operator >= (Complex Z1,Complex Z2);

    friend int operator < (Complex Z1,Complex Z2);

    friend int operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    21/77

    21

    Complex::Complex() {

    Real = 0.0; Imaginary = 0.0; }

    Complex::Complex(double R,double I) {

    Real = R; Imaginary = I; }Complex::Complex(const Complex & Z) {

    Real = Z.Real; Imaginary = Z.Imaginary; }

    Complex::Complex(double R) {

    Real = R; Imaginary = 0.0; }void Complex::Print() {

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    22/77

    22

    Complex operator - (Complex Z1,Complex Z2) {

    Complex Tmp;

    Tmp.Real = Z1.Real - Z2.Real;Tmp.Imaginary = Z1.Imaginary - Z2.Imaginary;

    return Tmp; }

    Complex Complex::operator += (Complex Z) {

    Real += Z.Real;

    Imaginary += Z.Imaginary;

    return *this; }

    Complex Complex::operator -= (Complex Z) {Real -= Z.Real;

    Imaginary -= Z.Imaginary;

    return *this; }

    23

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    23/77

    23

    int operator == (Complex Z1,Complex Z2) {

    return (Z1.Real == Z2.Real) && (Z1.Imaginary ==Z2.Imaginary); }

    int operator != (Complex Z1,Complex Z2) {

    return (Z1.Real != Z2.Real) || (Z1.Imaginary !=Z2.Imaginary); }

    int operator > (Complex Z1,Complex Z2) {

    return Z1.Abs() > Z2.Abs(); }int operator >= (Complex Z1,Complex Z2) {

    return Z1.Abs() >= Z2.Abs(); }

    int operator < (Complex Z1,Complex Z2) {

    return Z1.Abs() < Z2.Abs(); }int operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    24/77

    25

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    25/77

    25

    26

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    26/77

    26

    8.6 A NNG HA CC TON T MT NGI

    Ton t mt ngi ca lp c a nng ha nhmt hm thnh vin khng c tham s hoc nhmt hm khng thnh vin vi mt tham s; Thams phi hoc l mt i tng lp hoc l mttham chiu n i tng lp.

    Ton t V d Ton t V d

    + +c ~ ~c- -c ! !a

    * *c ++ ++c, c++

    & &c -- --c, c--

    -> c->

    27

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    27/77

    27

    V d :thm ton t du tr mt ngi volp Complex

    Thm vo nh ngha lp Complex dng sauComplex operator();

    V phnnh ngha cc hm v ton t ca lp

    ta thmComplex Complex::operator - () {

    Complex Tmp;

    Tmp.R = -R;

    Tmp.I = -I;

    return Tmp; }

    28

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    28/77

    28

    8.7 A NNG HA MT S TON T C BIT

    Trong phn ny chng ta s tm hiu cch ci tmt vi ton t c bit nh () [] ++ -- , = ->

    Ton t []: Khi ci t cc lp vector hoc chui k t, chng

    ta cn phi truy cp n tng phn t ca chng,trong ngn ng C/C++ c ton t [] truy cpn mt phn t ca mng. y l ton t haingi, c dng a[b] v khi a nng ton t ny th

    hm ton t tng ng phi l thnh vin ca mtlp. V d : a nng ha ton t [] truy cp n

    mt phn t ca vector.

    29

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    29/77

    #include

    class Vector {

    private: int Size;

    int *Data;

    public: Vector(int S=2,int V=0);

    ~Vector();

    void Print() const;int & operator [] (int I);

    };

    Vector::Vector(int S,int V) {

    Size = S;Data=new int[Size];

    for(int I=0;I

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    30/77

    Vector::~Vector() {

    delete []Data;

    }void Vector::Print() const {

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    31/77

    int main() {

    Vector V(5,1);

    V.Print();for(int I=0;I

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    32/77

    Ton t ()

    Ton t () c dng gi hm, ton t ny gm

    hai ton hng: ton hng u tin l tn hm, tonhng th hai l danh sch cc tham s ca hm.Ton t ny c dng ging nh ton t [] v khia nng ton t ny th hm ton t tng ng

    phi l thnh vin ca mt lp. V d :a nng ha ton t () truy cp n

    phn t ca ma trn.

    33

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    33/77

    #include

    class Matrix {

    private: int Rows,Cols;

    int **Data;

    public:

    Matrix(int R=2,int C=2,int V=0);

    ~Matrix();

    void Print() const;int & operator () (int R,int C);

    };

    34Matrix::Matrix(int R int C int V) {

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    34/77

    Matrix::Matrix(int R,int C,int V) {

    int I,J;

    Rows=R;

    Cols=C;

    Data = new int *[Rows];

    int *Temp=new int[Rows*Cols];

    for(I=0;I

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    35/77

    void Matrix::Print() const {

    int I,J;

    for(I=0;I

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    36/77

    int main() {

    int I,J;

    Matrix M(2,3,1);cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    37/77

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    38/77

    39

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    39/77

    Point::Point(int A,int B) {

    X = A;

    Y = B; }Point Point::operator++() {

    ++X;

    ++Y;

    return *this; }

    Point Point::operator++(int){

    Point Tmp=*this; //Sao chp tng ang xt

    // vo tng tm thi trc khi thay i++X;

    ++Y;

    return Tmp; }

    40

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    40/77

    Point Point::operator--() {

    --X;

    --Y;return *this; }

    Point Point::operator--(int) {

    Point Tmp=*this; //Sao chp i tng ang xt vo

    //i tngtm thi trc khi thay i--X;

    --Y;

    return Tmp; }void Point::Print() const {

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    41/77

    int main() {

    Point P1(2,6),P2(5,8),P3,P4;

    cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    42/77

    Ton t xut

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    43/77

    Ti nh ngha ton t nhp >>

    nh ngha hm ton cc:istream& operator >> (istream&, Class&);

    class Point {

    public:

    Point (int x=0, int y=0)

    { Point::x = x; Point::y = y; }

    friend istream& operator >>

    (istream& is, Point& p)

    { coutp.x;coutp.y;

    }

    // ..private:

    int x, y;

    };

    void main() {

    Point p1, p2;coutp1;

    coutp2;

    }

    g

    44

    Khi t h

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    44/77

    Khi to ngm nh

    c nh ngha sn trong ngn ng:VD: Point p1(10,20); Point p2 = p1;

    S gy ra li (kt qu SAI) khi bn trong i tng c thnhphn d liu l con tr.

    VD: Matrix m(5,6); Matrix n = m;

    Li s xy ra do

    khi to ngmbng cch gntng ng tng

    thnh phn.

    45Chng 8

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    45/77

    Khi to ngm nh (cont..)

    Khi lp c thnh phn d liu con tr, phi nhngha hm Khi to sao chp

    class Point {

    int x, y;

    public:

    Point (int =0; int =0 );

    // Khong can th iet DN

    Point (const Point& p) {

    x= p.x;

    y = p.y;

    }

    // ..};

    //

    class Vector {

    //

    Vector(const Vector&);

    };

    Vector:: Vector (const Vector &m)

    {

    Size = m.Size;

    Data=new int[Size];

    for(int i=0;i

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    46/77

    Gn ngm nh

    c nh ngha sn trong ngn ng: Gn tng ng tng thnh phn. ngkhi i tng khng c d liu con tr.

    VD: Point p1(10,20); Point p2; p2 = p1;

    Khi thnh phn d liu c con tr, bt buc phi nh

    ngha php gn = cho lp.class Vector{

    //.Vector& operator = (const Vector &m) {

    if (Size == m.Size) { // phi khp

    for (int i = 0; i < Size; ++i) // sao chp cc phn tdata[i] = m.Data[i];}return *this;

    }};

    Hm

    thnh

    vin

    47

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    47/77

    8.8 Case Study: Array class

    Arrays in C++No range checking Cannot be compared meaningfully with ==

    No array assignment (array names const pointers)

    Cannot input/output entire arrays at once One element at a time

    Example:Implement anArray class with Range checking

    Array assignment Arrays that know their size Outputting/inputting entire arrays with>

    Array comparisons with == and !=

    48

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    48/77

    8.8 Case Study: Array class

    Copy constructor Used whenever copy of object needed

    Passing by value (return value or parameter)

    Initializing an object with a copy of anotherArray newArray( oldArray );

    newArray copy ofoldArray

    Prototype for classArrayArray( const Array & );

    Musttake reference

    Otherwise, pass by value

    Tries to make copy by calling copy constructor

    Infinite loop

    Outline49

    1 // Fig. 8.4: array1.h

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    49/77

    2003 Prentice Hall, Inc.All rights reserved.

    Outline

    array1.h (1 of 2)

    2 // Array class for storing arrays of integers.

    3 #ifndefARRAY1_H

    4 #defineARRAY1_H

    5

    6 #include

    7

    8 using std::ostream;

    9 using std::istream;

    10

    11 class Array {

    12 friendostream &operator( istream &, Array & );

    14

    15 public:

    16 Array( int = 10 ); // default constructor

    17 Array( const Array & ); // copy constructor

    18 ~Array(); // destructor

    19 int getSize() const; // return size

    20

    21 // assignment operator

    22 const Array &operator=( const Array & );23

    24 // equality operator

    25 booloperator==( const Array & ) const;

    26

    Most operators overloaded asmember functions (except, which must be non-

    member functions).

    Prototype for copy constructor.

    Outline50

    27 // inequality operator; returns opposite of == operator

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    50/77

    2003 Prentice Hall, Inc.All rights reserved.

    Outline

    array1.h (2 of 2)

    28 booloperator!=( const Array &right ) const

    29 {

    30 return ! ( *this == right ); // invokes Array::operator==

    31

    32 } // end function operator!=

    33

    34 // subscript operator for non-const objects returns lvalue

    35 int &operator[]( int );

    36

    37 // subscript operator for const objects returns rvalue

    38 constint &operator[]( int ) const;

    39

    40 private:

    41 int size; // array size

    42 int *ptr; // pointer to first element of array

    43

    44 }; // end class Array

    45

    46 #endif

    != operator simply returns

    opposite of== operator. Thus,only need to define the ==

    operator.

    Outline51

    1 // Fig 8.5: array1.cpp

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    51/77

    2003 Prentice Hall, Inc.All rights reserved.

    Outline

    array1.cpp (1 of 7)

    2 // Member function definitions for class Array

    3 #include

    4

    5 using std::cout;

    6 using std::cin;

    7 using std::endl;

    8

    9 #include

    10

    11 using std::setw;

    12

    13 #include // C++ standard "new" operator

    14

    15 #include // exit function prototype

    16

    17 #include"array1.h" // Array class definition

    18

    19 // default constructor for class Array (default size 10)

    20 Array::Array( int arraySize )

    21 {

    22 // validate arraySize23 size = ( arraySize >0 ? arraySize : 10 );

    24

    25 ptr = new int[ size ]; // create space for array

    26

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    52/77

    Outline53

    51 // return size of array

    52

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    53/77

    2003 Prentice Hall, Inc.All rights reserved.

    Outline

    array1.cpp (3 of 7)

    52 int Array::getSize() const

    53 {

    54 return size;

    55

    56 } // end function getSize

    57

    58 // overloaded assignment operator;

    59 // const return avoids: ( a1 = a2 ) = a3

    60 const Array &Array::operator=( const Array &right )

    61 {

    62 if ( &right != this ) { // check for self-assignment

    63

    64 // for arrays of different sizes, deallocate original

    65 // left-side array, then allocate new left-side array

    66 if ( size != right.size ) {

    67 delete [] ptr; // reclaim space

    68 size = right.size; // resize this object

    69 ptr = newint[ size ]; // create space for array copy

    70

    71 } // end inner if

    7273 for (int i = 0; i < size; i++ )

    74 ptr[ i ] = right.ptr[ i ]; // copy array into object

    75

    76 } // end outer if

    Want to avoid self-assignment.

    Outline54

    77

    78 * hi // bl f l

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    54/77

    2003 Prentice Hall, Inc.All rights reserved.

    Outline

    array1.cpp (4 of 7)

    78 return *this; // enables x = y = z, for example

    79

    80 } // end function operator=

    81

    82 // determine if two arrays are equal and

    83 // return true, otherwise return false

    84 bool Array::operator==( const Array &right ) const

    85 {

    86 if ( size != right.size )

    87 returnfalse; // arrays of different sizes

    88

    89 for ( int i = 0; i < size; i++ )

    90

    91 if ( ptr[ i ] != right.ptr[ i ] )92 return false; // arrays are not equal

    93

    94 returntrue; // arrays are equal

    95

    96 } // end function operator==

    97

    Outline55

    98 // overloaded subscript operator for non-const Arrays

    99 // f t t l l

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    55/77

    2003 Prentice Hall, Inc.All rights reserved.

    array1.cpp (5 of 7)

    99 // reference return creates an lvalue

    100 int &Array::operator[]( int subscript )

    101 {

    102 // check for subscript out of range error

    103 if ( subscript < 0 || subscript >= size ) {

    104 cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    56/77

    2003 Prentice Hall, Inc.All rights reserved.

    array1.cpp (6 of 7)

    116 // const reference return creates an rvalue

    117 const int &Array::operator[]( int subscript ) const

    118 {

    119 // check for subscript out of range error

    120 if ( subscript < 0 || subscript >= size ) {

    121 cout a.ptr[ i ];

    138

    139 return input; // enables cin >> x >> y;

    140

    141 } // end function

    Outline57

    142

    143 // l d d t t t f l A

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    57/77

    2003 Prentice Hall, Inc.All rights reserved.

    array1.cpp (7 of 7)

    143 // overloaded output operator for class Array

    144 ostream &operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    58/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_06.cpp

    (1 of 3)

    2 // Array class test program.

    3 #include

    4

    5 using std::cout;

    6 using std::cin;

    7 using std::endl;

    8

    9 #include "array1.h"

    10

    11 int main()

    12 {

    13 Array integers1( 7 ); // seven-element Array

    14 Array integers2; // 10-element Array by default

    1516 // print integers1 size and contents

    17 cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    59/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_06.cpp

    (2 of 3)

    27 cout > integers1 >> integers2;

    29

    30 cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    60/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_06.cpp

    (3 of 3)

    49 cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    61/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_06.cpp

    output (1 of 3)

    Size of array integers1 is 7

    Array after initialization:

    0 0 0 0

    0 0 0

    Size of array integers2 is 10

    Array after initialization:

    0 0 0 0

    0 0 0 0

    0 0

    Input 17 integers:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

    After input, the arrays contain:

    integers1:

    1 2 3 4

    5 6 7

    integers2:

    8 9 10 11

    12 13 14 15

    Outline62Evaluating: integers1 != integers2

    integers1 and integers2 are not equal

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    62/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_06.cpp

    output (2 of 3)

    integers1 and integers2 are not equal

    Size of array integers3 is 7

    Array after initialization:

    1 2 3 4

    5 6 7

    Assigning integers2 to integers1:

    integers1:

    8 9 10 11

    12 13 14 15

    16 17

    integers2:

    8 9 10 1112 13 14 15

    16 17

    Evaluating: integers1 == integers2

    integers1 and integers2 are equal

    integers1[5] is 13

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    63/77

    64

    8 11 O erloading ++ and

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    64/77

    8.11 Overloading ++ and --

    Increment/decrement operators can be overloaded Add 1 to a Date object, d1

    Prototype (member function) Date &operator++();

    ++d1 same as d1.operator++()

    Prototype (non-member) Friend Date &operator++( Date &);

    ++d1 same as operator++( d1 )

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    65/77

    66

    8 11 Overloading ++ and

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    66/77

    8.11 Overloading ++ and --

    Return values Preincrement

    Returns by reference (Date &)

    lvalue (can be assigned)

    Postincrement

    Returns by value

    Returns temporary object with old value

    rvalue (cannot be on left side of assignment)

    Decrement operator analogous

    67

    8 12 Case Study: A Date Class

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    67/77

    8.12 Case Study: A Date Class

    Example Date class Overloaded increment operator

    Change day, month and year

    Overloaded += operator

    Function to test for leap years

    Function to determine if day is last of month

    Outline68

    1 // Fig. 8.10: date1.h

    2 // D t l d fi iti

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    68/77

    2003 Prentice Hall, Inc.

    All rights reserved.

    date1.h (1 of 2)

    2 // Date class definition.

    3 #ifndef DATE1_H

    4 #define DATE1_H

    5 #include

    67 using std::ostream;

    8

    9 class Date {

    10 friendostream &operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    69/77

    2003 Prentice Hall, Inc.All rights reserved.

    date1.h (2 of 2)

    24 private:

    25 int month;

    26 int day;

    27 int year;

    2829 static const int days[]; // array of days per month

    30 voidhelpIncrement(); // utility function

    31

    32 }; // end class Date

    33

    34 #endif

    Outline70

    1 // Fig. 8.11: date1.cpp

    2 // Date class member function definitions

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    70/77

    2003 Prentice Hall, Inc.All rights reserved.

    date1.cpp (1 of 5)

    2 // Date class member function definitions.

    3 #include

    4 #include "date1.h"

    5

    6 // initialize static member at file scope;7 // one class-wide copy

    8 const int Date::days[] =

    9 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    10

    11// Date constructor

    12 Date::Date( int m, int d, int y )

    13 {

    14 setDate( m, d, y );

    15

    16 } // end Date constructor

    17

    18 // set month, day and year

    19 voidDate::setDate( int mm, int dd, int yy )

    20 {

    21 month = ( mm >= 1 && mm = 1900 && yy

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    71/77

    2003 Prentice Hall, Inc.All rights reserved.

    date1.cpp (2 of 5)

    26 day = ( dd >= 1 && dd = 1 && dd

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    72/77

    2003 Prentice Hall, Inc.All rights reserved.

    date1.cpp (3 of 5)

    53 // add specified number of days to date

    54 const Date &Date::operator+=( int additionalDays )

    55 {

    56 for ( int i = 0; i < additionalDays; i++ )

    57 helpIncrement();

    58

    59 return *this; // enables cascading

    60

    61 } // end function operator+=

    62

    63 // if the year is a leap year, return true;

    64 // otherwise, return false65 bool Date::leapYear( int testYear ) const

    66 {

    67 if ( testYear % 400 == 0 ||

    68 ( testYear % 100 != 0 && testYear % 4 == 0 ) )

    69 returntrue; // a leap year

    70 else71 returnfalse; // not a leap year

    72

    73 } // end function leapYear

    74

    Outline73

    75 // determine whether the day is the last day of the month

    76 bool Date::endOfMonth( int testDay ) const

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    73/77

    2003 Prentice Hall, Inc.All rights reserved.

    date1.cpp (4 of 5)

    ( y )

    77 {

    78 if ( month == 2 && leapYear( year ) )

    79 return testDay == 29; // last day of Feb. in leap year

    80 else

    81 return testDay == days[ month ];

    82

    83 } // end function endOfMonth

    84

    85 // function to help increment the date

    86 voidDate::helpIncrement()

    87 {88 // day is not end of month

    89 if ( !endOfMonth( day ) )

    90 ++day;

    91

    92 else

    9394 // day is end of month and month < 12

    95 if ( month < 12 ) {

    96 ++month;

    97 day = 1;

    98 }

    99

    Outline74

    100 // last day of year

    101 else {

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPPhttp://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_5.CPP
  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    74/77

    2003 Prentice Hall, Inc.All rights reserved.

    date1.cpp (5 of 5)

    {

    102 ++year;

    103 month = 1;

    104 day = 1;

    105 }

    106

    107 } // end function helpIncrement

    108

    109 // overloaded output operator

    110 ostream &operator

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    75/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_12.cpp

    (1 of 2)

    p g

    3 #include

    4

    5 using std::cout;

    6 using std::endl;

    7

    8 #include"date1.h" // Date class definition

    9

    10 int main()

    11 {

    12 Date d1; // defaults to January 1, 1900

    13 Date d2( 12, 27, 1992 );14 Date d3( 0, 99, 8045 ); // invalid date

    15

    16 cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    76/77

    2003 Prentice Hall, Inc.All rights reserved.

    fig08_12.cpp

    (2 of 2)

    27 cout

  • 7/28/2019 Chuong VIII Da Nang Hoa Toan Tu

    77/77

    fig08_12.cpp

    output (1 of 1)

    d2 is December 27, 1992

    d3 is January 1, 1900

    d2 += 7 is January 3, 1993

    d3 is February 28, 1992

    ++d3 is February 29, 1992

    Testing the preincrement operator:

    d4 is July 13, 2002

    ++d4 is July 14, 2002

    d4 is July 14, 2002

    Testing the postincrement operator:

    d4 is July 14, 2002

    d4++ is July 14, 2002d4 is July 15, 2002

    http://localhost/var/www/apps/conversion/lthdt/Htm/Source/CT4_7.CPP