Upload
douglas-harrell
View
226
Download
1
Embed Size (px)
Citation preview
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
Expressions• Operator types• Unary• takes only a single operand• e.g., !
• Binary• takes two operands• e.g., + * / %
3
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
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
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
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
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
Relational & Logical Operators• Interesting info• Relational operators do not chain• <, <=, =>, >• e.g., a < b < c < d will not compile• associativity is irrelevant
9
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Operator Overloading• Operators you should define• if it makes sense
• For use with STL• < • ==• != : to go along with ==
• To print your class• <<
26
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
Operator Overloading
28
ostream& operator<<(ostream& os, const Book& book){ os << book.author_ << “ “; os << book.title_ << “ “; os << book.retail_price_;}
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
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
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);};