Post on 12-Jan-2016

25 views

Category:

## Documents

DESCRIPTION

TRANSCRIPT

• 7.1 IntroductionOperators

How about object variables?String operators*string s1 = "ABC";string s2 = s1 + "DEF";cout

• The Rational Class *1/2, 1/3, 11/12,Rational.cppRunRational.hTestRationalClass.cpp

Rational

-numerator: long

-denominator: long

+Rational()

+Rational(numerator: long, denominator: long)

+getNumerator(): long

+getDenominator(): long

+subtract(secondRational: Rational &): Rational

+multiply(secondRational: Rational &): Rational

+divide(secondRational: Rational &): Rational

+compareTo(secondRational: Rational &): int

+equals(secondRational: Rational &): bool

+intValue(): int

+doubleValue(): double

+toString(): string

-gcd(n: long, d: long): long

• Operation of the Rational Class*Rational Rational::add(Rational &secondRational) {long n = numerator * secondRational.getDenominator() + denominator * secondRational.getNumerator();long d = denominator * secondRational.getDenominator();return Rational(n, d);}Rational Rational::subtract(Rational &secondRational){long n = numerator * secondRational.getDenominator() - denominator * secondRational.getNumerator();long d = denominator * secondRational.getDenominator();return Rational(n, d);} cout
• Operator Functions The functions to overload operators*bool Rational::operator< (Rational &secondRational){ if (this->compareTo(secondRational) < 0) return true; else return false;}if(r1 < r2) cout

Can also be friends:

*type classname :: operator op(arglis){ Function body // task defined}vector operator+ (vector); // vector additionvector operator- (); // unary minusfriend vector operator+ (vector, vector);//vector additionfriend vector operator- (vector); // unary minus

• 7.2 Overloading Unary Operators+ and - --no parameters*Overloading Unary Minusvoid space :: operator-(){ x=-x; y=-y; z=-z;}//declarationfriend void operator-(space &s);//definition void operator-(space &s) { s.x=-s.x; s.y=-s.y; s.z=-s.z;}

*++r1

r1++Rational Rational::operator++() { numerator += denominator; return *this; } Rational Rational::operator++(){ Rational temp(numerator, denominator); numerator += denominator; return temp;}(int dummy){Same signature,How to distinguish them?,the value is never used;It must be int.Same signature,How to distinguish them?

• Overloading []The array subscript [] is an operator Can be overloaded to access the members of an object*long Rational::operator[](const int &index){ if (index == 0) return numerator; else if (index == 1) return denominator; else{ cout
• [] Accessor and MutatorThe [] operator functions as both accessor and mutator. After adding this operator to the Rational class, the Rational class is mutable.

*Rational r4(1, 2); r4[0] = 3; r4[1] = 4;long &Rational::operator[](const int &index)

Rational

-numerator: long

-denominator: long

+Rational()

+Rational(numerator: long, denominator: long)

+getNumerator(): long

+getDenominator(): long

+subtract(secondRational: Rational &): Rational

+multiply(secondRational: Rational &): Rational

+divide(secondRational: Rational &): Rational

+compareTo(secondRational: Rational &): int

+equals(secondRational: Rational &): bool

+intValue(): int

+doubleValue(): double

+toString(): string

-gcd(n: long, d: long): long

• 7.3 Overloading Binary Operators*Overloading + operator//functional notationC = sum ( A, B);//arithmetic notationC = A + B; complex complex :: operator+(complex c){ complex temp; temp.x = x + c.x; temp.y = y + c.y; return(temp); }

• Operands of Binary OperatorsFeatures:Only one complex argumentReturns a complex type valueA member function of complex

*complex complex :: operator+(complex c){ complex temp; temp.x = x + c.x; temp.y = y + c.y; return(temp); }C3 = C1 + C2; C3 = C1.operator+(C2);

• Operands of Binary Operators*

complex complex :: operator+(complex c){ complex temp;

temp.x = c.x + x; temp.y = c.y + y;

return(temp);}

4.106.20temp4.10 x6.20 yC32.50 x3.50 yC11.60 x2.70 yC2;+=Fig.7.1 Implementation of the overload + operator

• NotesThe left operand is fixed to be the operating object automatically c1 = c2 + c3 ; c1 = c2.operator+(c3); The number of parameters is determined by the operator itselfYou cannot change itOverloading does not change the operator precedence and associativity The (return) type of the operator function can be defined by youUsually the same class type to be operational in complex operation*

• 7.4 Overloading Other Operators*+=, -=, *=, /= Rational Rational::operator +=(Rational &secondRational){ *this = this->add(secondRational); return (*this);}Rational r1(2, 4);Rational r2 = r1 += Rational(2, 3);cout
• Overloading =By default, = performs a memberwise copyFor Rational class, it is OK.

How about others?*Rational r1(1, 2);Rational r2(4, 5);r1 = r2;class Person{private: int id; Date* birthDate; };p1 = p2;

person1: Person

id = 111

birthDate

111

: BirthDate

year = 1963

month = 5

day = 3

Memory

111

reference

Memory

person2: Person

id = 111

birthDate

reference

• Overloading =*const Person Person::operator=(const Person &p){id = p.id;Date *p=p.getBirthDate();birthDate = new Date(*p);return *this;}

• Friend: the left-hand operand as an argument

*Friend vs. MemberC3 = C1 + C2 C3 = C1.operator+(C2)C3 = C1 + 2 C3 = C1.operator+(2)C3 = 2 + C1 C3 = 2.operator+(C1) ???C3 = 2 + C1 C3 = operator+(2, C1)friend complex operator+(complex a, complex b);complex operator+(complex a, complex b) { return complex((a.x+b.x),(a.y+b.y)); }

• Two versions p = 2 * m;//equivalent to p = operator*(2,m) q = n * 2;//equivalent to q = operator*(n,2)By overloading >> and >(istream&, vector&); friend ostream& operator and
• Manipulation of StringsTo define operators to manipulate the stringsFor example:string3 = string1 + string2; if( string1 >= string2 ) string = string1;An example program overloads + and

:: ..*? :#sizeofA friend cannot be used:

=( )[ ]->

+ - * / % ^ & | ~ ! =

< > += -= *= /= %= ^= &= |= > >>= [] () new delete

• 7.5 Type ConversionsAutomatic type conversion for built-in typesConstants and variables of different types are mixed in an expressionRight type of an assignment operator = to the leftFor example,int m;float x = 3.14159;m = x;What happens when they are user-defined data types? Using Casting operator or Constructor*

• Three types of situationsConversion from basic type to class typeConversion from class type to basic typeConversion from one class type to another class type*

• Basic to Class TypeImplemented by using constructors with single argument*string::string (char * a){ length = strlen(a); p = new char[length+1]; strcpy(p, a);}string s1,s2;char* name1 = IBM PC;char* name2 = Apple;s1 = string(name1);s2 = name2;

• Class to Basic TypeBy defining an overloaded casting operatorUsually referred to as a conversion function:

*operator typename(){ ...... ......(Function statements)} Rational::operator double(){ return numerator/denominator;} int main(){ Rational r(2,3); double d = r;} string:: operator char*(){ return (p);}

• Notes on class basic typeIt must be a class memberIt must not specify a return typeIt must not have any arguments*

• One Class to Another Class TypeBy either a constructor or a conversion function

*objx = objy // Y is a source classCasting operator functionData access functionsConstructor functionClass XArgument of type Y Class YConversion here (destination class)Conversion here (source class)Class YConverted value of type XFig.7.2 Conversion between object

• An Example of Class to ClassA data conversion exampleFrom invent1 to invent2*Data conversions //constructor for conversion//invent2(invent1 p){ code = p.getcode(); value =p.getitems() * p.getprice(); } //operator function for conversionoperator invent2(){ invent2 temp; temp.code = code; temp.value = price * items; return temp; }

• Summary of all the three conversions*

Conversion requiredConversion takes place inSource classDestination classBasic ClassNot applicableConstructorClass BasicCasting operatorNot applicableClass ClassCasting operatorConstructor