Oop operator Overload

download Oop operator Overload

of 44

Transcript of Oop operator Overload

  • 8/10/2019 Oop operator Overload

    1/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note1

    Lecture 10

    Operator OverloadingShiow-yang Wu

    Department of Computer Science andInformation Engineering

    National Dong Hwa University

    Object-Oriented Programming in C++ Operator Overloading 2

    OperatorsOperators +, -, %, ==, etc.

    Really just functions !

    Simply called with different syntax: x + 7 + is binary operator with x and 7 as operandsWe "like" this notation as humans

    Think of it as: +(x, 7) + is the function namex, 7 are the argumentsFunction + returns sum of it s arguments

  • 8/10/2019 Oop operator Overload

    2/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note2

    Object-Oriented Programming in C++ Operator Overloading 3

    Operator OverloadingBuilt-in operators

    e.g.: +, -, = , %, ==, /, * Already work for C++ built-in typesIn standard "binary" notation

    We can overload them!To work with OUR types!

    To add Point types , or Money types As appropriate for our needsIn notation we re comfortable with

    Always overload with similar "actions"!

    Object-Oriented Programming in C++ Operator Overloading 4

    Overloading BasicsOverloading operators

    VERY similar to overloading functionsOperator itself is the name of function

    Example: Money '+'

    +MoneyMoney

    Money

  • 8/10/2019 Oop operator Overload

    3/44

  • 8/10/2019 Oop operator Overload

    4/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note4

    Object-Oriented Programming in C++ Operator Overloading 7

    Overloading Unary Operators. . .class Counter {

    private:unsigned int count; // count

    public:Counter() : count(0) // constructor

    { }unsigned int get_count()

    { return count; }void operator ++ () // increment (prefix)

    { ++count; }};

    Object-Oriented Programming in C++ Operator Overloading 8

    Overloading Unary Operatorsint main(){

    Counter c1, c2;

    ++c1; //increment c1

    ++c2; //increment c2++c2; //increment c2

    cout

  • 8/10/2019 Oop operator Overload

    5/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note5

    Object-Oriented Programming in C++ Operator Overloading 9

    The operator KeywordThe keyword operator is used to overload the ++operator in the following declarator:

    void operator ++ ()

    This declarator tells the compiler to call this memberfunction whenever the ++ operator is encountered,provided the operand is of type Counter .If the operand is an int variable intvar , as in

    ++intvar;then the normal increment operation is used.

    Object-Oriented Programming in C++ Operator Overloading 10

    The operator KeywordBut if the operand is a Counter variable, as in

    ++c1;then the user-defined operator++() is used.Note that operator++() takes no arguments. It

    simply increments the count data in the object ofwhich it is a member.For example, in the following statement

    ++c1;it will increment the count data in c1 .

  • 8/10/2019 Oop operator Overload

    6/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note6

    Object-Oriented Programming in C++ Operator Overloading 11

    Operator Return ValuesThe operator++() function in previous exampledoes not allow assignment statement such as

    c1 = ++c2;

    To make this possible, we must provide a way for thefunction to return a value.

    . . .class Counter {

    private:unsigned int count; //count public:

    Counter() : count(0) //constructor{ }

    Object-Oriented Programming in C++ Operator Overloading 12

    Operator Return Valuesunsigned int get_count()

    { return count; }Counter operator ++ () //increment

    {

    ++count; //increment countCounter temp; //temp Countertemp.count = count;return temp; //return the copy}

    };

  • 8/10/2019 Oop operator Overload

    7/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note7

    Object-Oriented Programming in C++ Operator Overloading 13

    Nameless Temporary ObjectThere are more convenient ways to return temporaryobjects without giving them names.

    #include using namespace std;class Counter{

    private:unsigned int count; //count

    public:Counter() : count(0) //constructor

    { }

    Object-Oriented Programming in C++ Operator Overloading 14

    Nameless Temporary ObjectCounter(int c) : count(c)

    { }int get_count() //return count

    { return count; }Counter operator ++ () //increment

    {++count; //increment countreturn Counter(count);}

    };

  • 8/10/2019 Oop operator Overload

    8/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note8

    Object-Oriented Programming in C++ Operator Overloading 15

    Nameless Temporary Objectint main(){

    Counter c1, c2; //c1=0, c2=0

    cout

  • 8/10/2019 Oop operator Overload

    9/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note9

    Object-Oriented Programming in C++ Operator Overloading 17

    Postfix NotationThe operators defined in previous examples onlyallow prefix operation .To allow postfix operation such as

    c1++;

    we need to define a separate operator for it.class Counter{

    private:unsigned int count; // count

    public:Counter() : count(0) // constructor

    { }

    Object-Oriented Programming in C++ Operator Overloading 18

    Postfix NotationCounter(int c) : count(c) // constructor

    { }unsigned int get_count() const

    { return count; }

    Counter operator ++ () // increment (prefix){ return Counter(++count); }

    Counter operator ++ (int) // inc. (postfix){ return Counter(count++); }

    };// the (int) is NOT an argument but simply

    // indicates a postfix operator

  • 8/10/2019 Oop operator Overload

    10/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note10

    Object-Oriented Programming in C++ Operator Overloading 19

    Postfix Notationint main(){

    Counter c1, c2; //c1=0, c2=0

    cout

  • 8/10/2019 Oop operator Overload

    11/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note11

    Object-Oriented Programming in C++ Operator Overloading 21

    Overloading Arithmetic

    OperatorsBy overloading arithmetic operator such as +, we canreduce the obscure statement

    dist3.add(dist1, dist2);

    into much more natural looking expressiondist3 = dist1 + dist2;

    Lets look at an example:class Distance { //English Distance class

    private:int feet;float inches;

    Object-Oriented Programming in C++ Operator Overloading 22

    Overloading ArithmeticOperators

    public:Distance() : feet(0), inches(0.0)

    { }Distance(int ft, float in) :

    feet(ft), inches(in)

    { }void showdist() const {

    cout

  • 8/10/2019 Oop operator Overload

    12/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note12

    Object-Oriented Programming in C++ Operator Overloading 23

    Overloading Arithmetic

    OperatorsDistance Distance::operator + (Distance d2)const //add Distance{int f = feet + d2.feet;float i = inches + d2.inches;if(i >= 12.0) {

    i -= 12.0;f++;

    } //return a temporary Distancereturn Distance(f,i);

    }

    Object-Oriented Programming in C++ Operator Overloading 24

    Overloading ArithmeticOperatorsint main(){

    Distance dist1(10, 6.5), dist2(11, 6.25);Distance dist3, dist4;

    dist3 = dist1 + dist2; // '+' operatordist4 = dist1 + dist2 + dist3;

    cout

  • 8/10/2019 Oop operator Overload

    13/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note13

    Object-Oriented Programming in C++ Operator Overloading 25

    Overloading Arithmetic

    OperatorsNote that in the expressiondist3 = dist1 + dist2;

    the operand on the left side of the operator ( dist1 )is the object of which the operator is a member.The object on the right side of the operator ( dist2 )is an argument to the operator.In general, an overloaded operator always requires

    one less argument than its number of operands,since one operand is the object of which the operatoris a member.

    Object-Oriented Programming in C++ Operator Overloading 26

    Overloading ArithmeticOperators

    This is why a unary operator requires no arguments(such as the ++ operator we discussed earlier).Similar functions could be created to overload otheroperators in the Distance class, so that you couldsubstract( - ), multiply( * ), and divide( / ) Distanceobjects in natural-looking ways.

  • 8/10/2019 Oop operator Overload

    14/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note14

    Object-Oriented Programming in C++ Operator Overloading 27

    Concatenating StringsWe can even overload the + operator for stringconcatenation as in str3 = str1 + str2;

    . . .#include #include class String { //user-defined string type

    private:static const int SZ = 80;char str[SZ]; //holds a C-string

    public:String()

    { strcpy(str, ""); }String( char s[] )

    { strcpy(str, s); }

    Object-Oriented Programming in C++ Operator Overloading 28

    Concatenating Stringsvoid display() const

    { cout

  • 8/10/2019 Oop operator Overload

    15/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note15

    Object-Oriented Programming in C++ Operator Overloading 29

    Overloading Comparison

    Operatorsclass Distance //English Distance class{

    private:int feet;float inches;

    public:Distance() : feet(0), inches(0.0)

    { }

    Distance(int ft, float in) :feet(ft), inches(in)

    { }

    Object-Oriented Programming in C++ Operator Overloading 30

    Overloading ComparisonOperators

    void getdist() {cout > feet;cout > inches;

    }void showdist() const {

    cout

  • 8/10/2019 Oop operator Overload

    16/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note16

    Object-Oriented Programming in C++ Operator Overloading 31

    Overloading Comparison

    Operators bool Distance::operator < (Distance d2) const//return true or false{float bf1 = feet + inches/12;float bf2 = d2.feet + d2.inches/12;return (bf1 < bf2) ? true : false;}

    int main(){

    Distance dist1;dist1.getdist();

    Object-Oriented Programming in C++ Operator Overloading 32

    Overloading ComparisonOperators

    Distance dist2(6, 2.5);

    cout

  • 8/10/2019 Oop operator Overload

    17/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note17

    Object-Oriented Programming in C++ Operator Overloading 33

    Comparing Strings#include //for strcmp()

    class String //user-defined string type{

    private:static const int SZ = 80;char str[SZ]; //holds a C-string

    public:

    String(){ strcpy(str, ""); }

    String( char s[] ){ strcpy(str, s); }

    Object-Oriented Programming in C++ Operator Overloading 34

    The == Operatorvoid display() const

    { cout

  • 8/10/2019 Oop operator Overload

    18/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note18

    Object-Oriented Programming in C++ Operator Overloading 35

    Arithmetic Assignment

    Operatorsclass Distance { //English Distance class private:

    int feet;float inches;

    public:Distance() : feet(0), inches(0.0)

    { }Distance(int ft, float in) :

    feet(ft), inches(in){ }

    void showdist() const{ cout

  • 8/10/2019 Oop operator Overload

    19/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note19

    Object-Oriented Programming in C++ Operator Overloading 37

    The Subscript Operator []In C++, even the subscript operator [] can beoverloaded. This is useful when you want to dosomething similar to arrays but in a different way.For example, we could modify the way arrays areaccessed in C++ by doing bound checking on eachaccess.For the overloaded subscript operator [] to be

    useful, it must return by reference such that it canbe placed at the left side of equal sign.

    Object-Oriented Programming in C++ Operator Overloading 38

    The Subscript Operator []We will discuss three different ways of accessingarray elements:

    separate member functions putel() andgetel()

    a single member function access() using returnby referencethe overloaded [] operator using return byreference

    All three programs check to ensure that all arrayaccesses are within bounds.

  • 8/10/2019 Oop operator Overload

    20/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note20

    Object-Oriented Programming in C++ Operator Overloading 39

    getel() and putel(). . .#include // for exit()const int LIMIT = 100;//////////////////////////////////////////class safearay1{

    private:int arr[LIMIT];

    public://set value of elementvoid putel (int n, int elvalue) {

    if( n < 0 || n >= LIMIT ) {

    Object-Oriented Programming in C++ Operator Overloading 40

    getel() and putel()cout = LIMIT ) {cout

  • 8/10/2019 Oop operator Overload

    21/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note21

    Object-Oriented Programming in C++ Operator Overloading 41

    getel() and putel()int main(){

    safearay1 sa1;

    for(int j=0; j

  • 8/10/2019 Oop operator Overload

    22/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note22

    Object-Oriented Programming in C++ Operator Overloading 43

    Single access() FunctionBy using the technique of return by reference , wecan use the same member function both to put andget elements from an array.

    #include using namespace std;#include //for exit()const int LIMIT = 100; //array size//////////////////////////////////////////class safearay2{

    private:

    int arr[LIMIT];

    Object-Oriented Programming in C++ Operator Overloading 44

    Single access() Function public:

    int& access(int n) // return by reference !{

    if( n < 0 || n >= LIMIT ) {

    cout

  • 8/10/2019 Oop operator Overload

    23/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note23

    Object-Oriented Programming in C++ Operator Overloading 45

    Single access() Functionint main(){

    safearay2 sa1;

    for(int j=0; j

  • 8/10/2019 Oop operator Overload

    24/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note24

    Object-Oriented Programming in C++ Operator Overloading 47

    Overloaded [] Operator#include using namespace std;#include //for exit()const int LIMIT = 100; //array size//////////////////////////////////////////class safearay{

    private:

    int arr[LIMIT]; public:

    int& operator [](int n) // return by reference

    {

    Object-Oriented Programming in C++ Operator Overloading 48

    Overloaded [] Operatorif( n < 0 || n >= LIMIT ) {

    cout

  • 8/10/2019 Oop operator Overload

    25/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note25

    Object-Oriented Programming in C++ Operator Overloading 49

    Overloaded [] Operatorint main(){

    safearay sa1;

    for(int j=0; j

  • 8/10/2019 Oop operator Overload

    26/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note26

    Object-Oriented Programming in C++ Operator Overloading 51

    Data ConversionWhen the value of one object is assigned to anotherof the same type, such as

    dist3 = dist1 + dist2;

    the values of all the member data items are simplycopied into the new object. The compiler knows howto do this automatically.Data conversion occurs when one type of data is

    assigned to another of different type.The conversion can be implicit (i.e. not apparent inthe code listing) such as

    intvar = floatvar;

    Object-Oriented Programming in C++ Operator Overloading 52

    Data ConversionCasting provides explicit conversion:

    intvar = static_cast (floatvar);

    For conversion of user-defined types, theprogrammers must define the conversion routines.

    Data conversion may seem unnecessarily complex oreven dangerous.However, the flexibility of provided by allowingconversions outweighs the dangers.

  • 8/10/2019 Oop operator Overload

    27/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note27

    Object-Oriented Programming in C++ Operator Overloading 53

    Objects Basic Types#include using namespace std;//////////////////////////////////////////class Distance { //English Distance class

    private:const float MTF; //meters to feetint feet;float inches;

    public:Distance() : feet(0), inches(0.0),

    MTF(3.280833F){ }

    Object-Oriented Programming in C++ Operator Overloading 54

    Objects Basic TypesDistance(float meters) : MTF(3.280833F)

    { //the conversion constructor//convert meters to Distance

    float fltfeet = MTF * meters;

    feet = int(fltfeet);inches = 12*(fltfeet-feet);}

    Distance(int ft, float in) :feet(ft), inches(in), MTF(3.280833F)

    { }

  • 8/10/2019 Oop operator Overload

    28/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note28

    Object-Oriented Programming in C++ Operator Overloading 55

    Objects Basic Typesvoid getdist() //get length from user

    {cout > feet;cout > inches;}

    void showdist() const //display{ cout

  • 8/10/2019 Oop operator Overload

    29/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note29

    Object-Oriented Programming in C++ Operator Overloading 57

    Objects Basic Typesint main(){

    float mtrs;

    //use 1-arg conversion constructor to convert//meters to DistanceDistance dist1 = 2.35F;cout

  • 8/10/2019 Oop operator Overload

    30/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note30

    Object-Oriented Programming in C++ Operator Overloading 59

    C-Strings String Objects// strconv.cpp// ordinary strings class String#include using namespace std;#include //for strcpy(), etc.//////////////////////////////////////////class String //user-defined string type{

    private:enum { SZ = 80 }; // size of all String objectschar str[SZ]; // holds a string

    Object-Oriented Programming in C++ Operator Overloading 60

    C-Strings String Objects public:

    String() // no-arg constructor{ str[0] = '\0'; }

    String( char s[] ) // 1-arg constructor{ strcpy(str, s); } // C-string -> String

    void display() const // display the String{ cout C-string

    };

  • 8/10/2019 Oop operator Overload

    31/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note31

    Object-Oriented Programming in C++ Operator Overloading 61

    C-Strings String Objectsint main(){

    String s1; // use no-arg constructor// create and initialize C-string

    char xstr[] = "Joyeux Noel! ";

    s1 = xstr; // use 1-arg constructor// to convert C-string to String

    s1.display(); // display String

    // uses 1-arg constructor to initialize StringString s2 = "Bonne Annee!";

    Object-Oriented Programming in C++ Operator Overloading 62

    C-Strings String Objects// use conversion operator to convert String to// C-string before sending to

  • 8/10/2019 Oop operator Overload

    32/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note32

    Object-Oriented Programming in C++ Operator Overloading 63

    Conversions Between

    Different ClassesFor conversions between objects of different classes,use the one-argument constructor or a conversionoperator depending on where we want to place ourconversion routine.Consider the statement:

    objecta = objectb;

    where objecta and objectb are members of class Aand B, respectively.

    If we want to place the conversion routine in the sourceclass (B), then a conversion operator is commonly used.If we want to place the conversion routine in thedestination class (A), then a one-argument constructor iscommonly used.

    Object-Oriented Programming in C++ Operator Overloading 64

    Conversions BetweenDifferent Classes

    Lets use the conversion between two kinds of timeas an example.

    12-hour Time 24-hour Time

    12:00 a.m. 00:00:00

    6:00 a.m. 06:00:0012:00 p.m. 12:00:006:00 p.m. 18:00:0011:59 p.m. 23:59:00

  • 8/10/2019 Oop operator Overload

    33/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note33

    Object-Oriented Programming in C++ Operator Overloading 65

    Routine in Source Class#include #include using namespace std;class time12{

    private: bool pm; //true = pm, false = am

    int hrs; //1 to 12

    int mins; //0 to 59, no seconds !! public:

    time12() : pm(true), hrs(0), mins(0)

    { }

    Object-Oriented Programming in C++ Operator Overloading 66

    Routine in Source Classtime12(bool ap, int h, int m) :

    pm(ap), hrs(h), mins(m){ }

    void display() const { // format: 11:59 p.m.cout

  • 8/10/2019 Oop operator Overload

    34/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note34

    Object-Oriented Programming in C++ Operator Overloading 67

    Routine in Source Classclass time24{

    private:int hours; //0 to 23int minutes; //0 to 59int seconds; //0 to 59

    public:time24() : hours(0), minutes(0), seconds(0)

    { }time24(int h, int m, int s) :

    hours(h), minutes(m), seconds(s)

    { }

    Object-Oriented Programming in C++ Operator Overloading 68

    Routine in Source Classvoid display() const // format: 23:15:01

    {if (hours < 10) cout

  • 8/10/2019 Oop operator Overload

    35/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note35

    Object-Oriented Programming in C++ Operator Overloading 69

    Routine in Source Classtime24::operator time12() const

    //conversion operator{

    int hrs24 = hours;

    //find am/pm bool pm = hours < 12 ? false : true;

    //round secsint roundMins = seconds < 30 ? minutes :

    minutes+1;

    Object-Oriented Programming in C++ Operator Overloading 70

    Routine in Source Classif (roundMins == 60) //carry mins?

    {roundMins=0;++hrs24;if (hrs24 == 12 || hrs24 == 24)

    pm = (pm==true) ? false : true;}

    int hrs12 = (hrs24 < 13) ? hrs24 : hrs24-12;

    if (hrs12==0) //00 is 12 a.m.{ hrs12=12; pm=false; }

    return time12(pm, hrs12, roundMins);}

  • 8/10/2019 Oop operator Overload

    36/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note36

    Object-Oriented Programming in C++ Operator Overloading 71

    Routine in Source Classint main(){

    int h, m, s;

    while(true){ //get 24-hr time from usercout h;

    if (h > 23) //quit if hours > 23return(1);

    cout > m;cout > s;

    Object-Oriented Programming in C++ Operator Overloading 72

    Routine in Source Classtime24 t24(h, m, s); //make a time24cout

  • 8/10/2019 Oop operator Overload

    37/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note37

    Object-Oriented Programming in C++ Operator Overloading 73

    Routine in Destination Class. . .class time24 {

    private:int hours; //0 to 23int minutes; //0 to 59int seconds; //0 to 59

    public:time24() : hours(0), minutes(0), seconds(0)

    { }time24(int h, int m, int s) :

    hours(h), minutes(m), seconds(s){ }

    Object-Oriented Programming in C++ Operator Overloading 74

    Routine in Destination Classvoid display() const { // format 23:15:01

    if (hours < 10) cout

  • 8/10/2019 Oop operator Overload

    38/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note38

    Object-Oriented Programming in C++ Operator Overloading 75

    Routine in Destination Classclass time12{

    private: bool pm; //true = pm, false = am

    int hrs; //1 to 12int mins; //0 to 59

    public:time12() : pm(true), hrs(0), mins(0)

    { }time12(time24); //1-arg constructor

    Object-Oriented Programming in C++ Operator Overloading 76

    Routine in Destination Classtime12(bool ap, int h, int m) : //3-arg

    pm(ap), hrs(h), mins(m){ }

    void display() const{cout

  • 8/10/2019 Oop operator Overload

    39/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note39

    Object-Oriented Programming in C++ Operator Overloading 77

    Routine in Destination Classtime12::time12( time24 t24 )

    { //converts time24 to time12int hrs24 = t24.getHrs(); //get hours

    //find am/pm pm = t24.getHrs() < 12 ? false : true;

    //round secs mins = (t24.getSecs() < 30) ?

    t24.getMins() : t24.getMins()+1;

    Object-Oriented Programming in C++ Operator Overloading 78

    Routine in Destination Classif (mins == 60) //carry mins?

    { mins = 0;

    ++hrs24;if (hrs24 == 12 || hrs24 == 24)

    pm = (pm == true) ? false : true;}

    hrs = (hrs24 < 13) ? hrs24 : hrs24-12;if (hrs == 0) //00 is 12 a.m.

    { hrs = 12; pm = false; }

    }

  • 8/10/2019 Oop operator Overload

    40/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note40

    Object-Oriented Programming in C++ Operator Overloading 79

    Routine in Destination Classint main(){

    int h, m, s;

    while(true){ //get 24-hour time from usercout h;

    if (h > 23) //quit if hours > 23return(1);

    cout > m;cout > s;

    Object-Oriented Programming in C++ Operator Overloading 80

    Routine in Destination Classtime24 t24(h, m, s); //make a time24cout

  • 8/10/2019 Oop operator Overload

    41/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note41

    Other Overloads&&, ||, and comma operator

    Predefined versions work for bool typesRecall: use "short-circuit evaluation"When overloaded no longer usesshort-circuit

    Uses "complete evaluation" insteadContrary to expectations

    Generally should not overloadthese operators

    Object-Oriented Programming in C++ Operator Overloading 81

    Object-Oriented Programming in C++ Operator Overloading 82

    Pitfalls of Op Overloadingand Conversion

    Operator overloading and type conversions give youthe power to extend the C++ language and to makeyour program listing more intuitive.They can make your listing more obscure and hard tounderstand too, it not used properly.Guidelines:

    Use similar meaningsUse similar syntaxShow restraint (too much of a good thing is bad)

    Avoid ambiguity (avoid doing the same conversion in morethan one way)

  • 8/10/2019 Oop operator Overload

    42/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note42

    Object-Oriented Programming in C++ Operator Overloading 83

    Pitfalls of Op Overloading

    and ConversionNote that you cant overload a binary operator to bea unary operator, or vice versa.The following operators cannot be overloaded:

    dot operator ( . )scope resolution operator ( :: )conditional operator ( ?: )pointer-to-member operator ( -> )

    You cant create new operator (like *&) and try tooverload them; only existing operators can beoverloaded.

    Object-Oriented Programming in C++ Operator Overloading 84

    Assignment 71. A complex ("imaginary ") number has the form a + bi , where i

    is the square root of -1. Here, a is called the real part and b is called the imaginary part . Alternatively, a + bi can beexpressed as the ordered pair of real numbers (a, b).

    Arithmetic operations on two complex numbers (a, b) and (c,

    d) are as follows:(a, b) + (c, d) = (a + c, b + d)(a, b) - (c, d) = (a - c, b - d)(a, b) * (c, d) = (a*c - b*d, a*d + b*c)(a, b) / (c, d) = ((a*c + b*d)/(c 2 + d 2), (b*c - a*d)/(c 2 + d 2))

    Also, the absolute value (or magnitude ) of a complex numberis defined as| (a, b) | = sqrt(a 2 + b 2)

  • 8/10/2019 Oop operator Overload

    43/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Note43

    Object-Oriented Programming in C++ Operator Overloading 85

    Assignment 7Design, implement, and test a complex numberclass that represents the real and imaginary parts asdouble precision values (data type doubl e ) andprovides at least the following operations:

    constructors for explicit as well as defaultinitialization. The default initial value should be (0.0, 0.0).arithmetic operations that add, subtract, multiply, anddivide two complex numbers. These should beimplemented as value-returning functions , each returning

    a class object.a complex absolute value operation as a value-returnfunctiontwo accessor functions, Real Par t and I magPar t , thatreturn the real and imaginary parts of a complex number.

    Object-Oriented Programming in C++ Operator Overloading 86

    Assignment 72. Modify your complex number class designed above

    by overloading the arithmetic operators (+, -, *, /)to work on complex numbers. In addition to thearithmetic operators, also overload the equals (==),not equal (!=), and unary minus (-) for the complexnumber class. Note that complex numbers x = a +bi and y = c + di are equal if and only if a equals c and b equals d . If x = a + bi is a complex number,-x equals -a - bi .

  • 8/10/2019 Oop operator Overload

    44/44

    CSIEB0040 Object-Oriented Programming in C++ Lecture10 Operator Overloading

    Object-Oriented Programming in C++ Operator Overloading 87

    Assignment 73. Augment the saf ear ay class discussed in the class

    so that the user can specify both the upper andlower bound of the array (indexes running from 100to 200, for example). Have the overloaded subscriptoperator check the index each time the array isaccessed to ensure it is not out of bounds. You'llneed to add a two-argument constructor thatspecifies the upper and lower bounds. Since wehave not yet learned how to allocate memorydynamically, the member data will still be an arraythat starts at 0 and runs up to 99, but perhaps youcan map the indexes for the saf ear ay into differentindexes in the real int array. For example, if theclient selects a range from 100 to 175, you couldmap this into the range from arr[0] to arr[75].

    Object-Oriented Programming in C++ Operator Overloading 88

    Assignment 74. Modify your Pol ynomi al class in assignment 6 by

    providing the following overloaded operators: Addition operator (+) to add two PolynomialsSubtraction operator (-) to subtract two Polynomials

    Assignment operator (=) to assign one Polynomial to

    anotherMultiplication operator (*) to multiply two Polynomials Addition assignment operator (+=), the subtractionassignment operator (-=), and the multiplicationassignment operator (*=)

    (Write test programs for all your classes.)

    Due: May 28, 2012