Top Banner
Operators & Overloading Joe Meehean
32

Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Dec 27, 2015

Download

Documents

Douglas Harrell
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
Page 1: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operators & Overloading

Joe Meehean

Page 2: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Expressions• Expression composed of operands combined with operators• e.g., a + b

• Operands• variables and literals in an expression• e.g., a b

• Operators• symbol that combine the operands• e.g., + - / * %

• Result• what is left after evaluating expression• result of applying operators to operands

2

Page 3: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Expressions• Operator types• Unary• takes only a single operand• e.g., !

• Binary• takes two operands• e.g., + * / %

3

Page 4: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Expressions• How are expressions evaluated?• Depends on associativity and precedence• Precedence• if expression contains more than 1 operator• which operator to apply first• operators with higher precedence applied first• e.g., 7 + 3 * 5 == 7 + (3 * 5)

4

Page 5: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Expressions• How are expressions evaluated?• Depends on associativity and precedence• Associativity• given multiple operators with the same precedence• which operator to apply first• depends on associativity

• Left associative• apply operators from left to right• e.g., 2 + 3 + 5 == (2 + 3) + 5

• Right associative• apply operators from right to left• e.g., 2 + 3 + 5 == 2 + (3 + 5) 5

Page 6: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Arithmetic Operators

6

Operator Function Associativity Level *

+ unary plus R 1

− unary minus R 1

* multiplication L 6

/ division L 6

% modulo L 6

+ addition L 7

− subtraction L 7

* lower level == higher precedence. Level 1 has highest precedence

Page 7: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Arithmetic Operators• Dangers• Illegal operations• e.g., division by 0• causes program to crash

• Overflow• value goes outside of legal range• 2 byte signed short max value: 32767

• 2^15 (16th bit reserved for sign)• adding one pushes a 1 into the sign position• causes value to go negative: - 32768

7

Page 8: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Relational & Logical Operators

8

Operator Function Associativity Level *

! logical not R 3

<, <= less than (equal) L 9

>, >= greater than (equal) L 9

==, != (not) equals L 10

&& logical and L 14

|| logical or L 15

* lower level == higher precedence. Level 1 has highest precedence

Page 9: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Relational & Logical Operators• Interesting info• Relational operators do not chain• <, <=, =>, >• e.g., a < b < c < d will not compile• associativity is irrelevant

9

Page 10: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Relational & Logical Operators• Interesting info• Short-circuit evaluation• given a series of conditions connected by ||• if any of the conditions is true, the expression is true• conditions only evaluated until the first true condition is found• e.g., a || b || c• if a is true, b and c won’t be evaluated• if a is false and b is true, only a and b will be evaluated

10

Page 11: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Relational & Logical Operators• Interesting info• Short-circuit evaluation• given a series of conditions connected by &&• expression true only if all conditions are true• conditions only evaluated until the first false condition is found• e.g., a && b && c• if a is false, b and c won’t be evaluated• if a is true and b is false, only a and b will be evaluated• power (avoid going out of bounds):while( i < theVector.size() && theVector[i] != 7){ i++;} 11

Page 12: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Bitwise Operators• AND• combines two bit sets• bit in result only 1 if both bits in operands are 1• e.g., 0101 AND 1100 => 0100

• OR• combines two bit sets• bit in result 1 if bit in either operand is 1• e.g., 0101 OR 1010 => 1111

12

Page 13: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Bitwise Operators• NOT• flips all of the bits• e.g., 0101 => 1010

• XOR• combines two bit sets• bit in results 1 only if exactly one bit in the operands was 1• e.g., 1010 XOR 1010 => 0000• e.g., 1110 XOR 1010 => 0100

13

Page 14: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Bitwise Operators• left shift• shifts all bits to the left• e.g., 0011 => 0110• new bits are zero• left-most bit falls off the end

• right shift• shifts all bits to the right• e.g., 0111 => 0011• new bits are zero• right-most bit falls off the end

14

Page 15: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Bitwise Operators

15

Operator Function Associativity Level *

~ bitwise NOT R 3

<<, >> left (right) shift L 8

& bitwise AND L 11

^ bitwise XOR L 12

| bitwise OR L 13

* lower level == higher precedence. Level 1 has highest precedence

Page 16: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

IO Operators• bitwise shift operators overloaded for IO• <<• insertion operator• inserts data into output stream• e.g., cout << a << endl;

• >>• extraction operator• extracts data from input stream• e.g., cin >> a ;

16

Page 17: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Other Operators

17

Operator Function Associativity Level *

() grouping L 2

++, -- postfix L 2

++, -- prefix R 3

* Lower level == higher precedence. Level 1 has highest precedence

Page 18: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Assignment Operators

18

Operator Function Associativity Level *

= assignment R 17

+=, −=, *=, /=, %=

arithmetic assignment

R 17

>>=, <<=, &=, |=, ^=

bitwise assignment R 17

* Lower level == higher precedence. Level 1 has highest precedence

Page 19: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Assignment Operators• Assignment operator has low precedence and is right

associative• very important

• Right associativity • allows: a = b = c = 0

• Low precedence• a = b + c => a = (b + c)• makes logical sense

19

Page 20: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Questions?

20

Page 21: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Redefine operators for classes we write• Lets us make intuitive use of operators• like [] for vector and string• += for string append

• Powerful and easy to read• v[i] vs. v.get(i)• str += “Hello” vs. str.append(“Hello”)

21

Page 22: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• 2 different types of operator overloading• Member overloading• defined as a member method of a class• first operand is always this• if binary operator, method takes 1 parameter

• the other operand• if unary operator, method takes 0 parameters• generally best choice for assignment/modifier operators

• =• +=, -=, …• []• ->

22

Page 23: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• 2 different types of operator overloading• Nonmember overloading• defined as a global function• if binary operator, method takes 2 parameter• if unary operator, method takes 1 parameters• generally best choice for symmetric operators

• arithmetic• equality• relational• bitwise

23

Page 24: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Syntax: member method• requires the operator keyword• type Class::operator +=(type)• e.g., bool UsedBook::operator ==(const UsedBook& rhs)

• Syntax: nonmember method• type1 operator +=(type, type)• e.g., bool operator==(const UsedBook& lhs, const UsedBook& rhs)

24

Page 25: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Limitations• can overload all operators discussed in class except:

:: , .* , . , ?:• cannot invent new operators: operator **• at least one operand must be a class• precedence and associativity cannot be changed

• Short-circuit evaluations is not preserved• &&, ||• both operands are always evaluate• evaluation order is not guaranteed

25

Page 26: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Operators you should define• if it makes sense

• For use with STL• < • ==• != : to go along with ==

• To print your class• <<

26

Page 27: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Overloading the output operator <<• Non-member method• 1st parameter is always a reference to an ostream• cout is an instance of the ostream class• reference because ostream cannot be copied

• 2nd parameter is often const reference to class object• printing an object rarely changes it• reference prevents making unnecessary copies

• Always returns an ostream reference• so we can chain << operators together• e.g., cout << a << b << c << endl

• Do not add an end line when writing operator << 27

Page 28: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading

28

ostream& operator<<(ostream& os, const Book& book){ os << book.author_ << “ “; os << book.title_ << “ “; os << book.retail_price_;}

Page 29: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Non-member function in previous example had access to

Book’s private member data. How?• Friends• class can call other classes or method friends• friends can access private member data and methods

• Syntax: friend classes• friend class class1• e.g., friend class Song

29

Page 30: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading• Non-member function in previous example had access to

Book’s private member data. How?• Friends• class can call other classes or method friends• friends can access private member data and methods

• Syntax: friend methods• friend return_type name(type1 var1, type2 var2,…)• e.g., friend ostream& operator<<(ostream& os, const Book& b);• does not declare this method• just says this method exists and is a friend

30

Page 31: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Operator Overloading

31

class Song{ private: string title_; string duration_s; string artist_;

public: Song(...); ...

// this is not declaring this method // this method is not a member method of Song friend ostream& operator<<(ostream& os, const Song& s);};

Page 32: Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Questions?

32