Download presentation
Presentation is loading. Please wait.
Published byDouglas Harrell Modified over 9 years ago
1
Operators & Overloading Joe Meehean
2
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
3
Expressions Operator types Unary takes only a single operand e.g., ! Binary takes two operands e.g., + * / % 3
4
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
5
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
6
Arithmetic Operators 6 OperatorFunctionAssociativityLevel * +unary plusR1 − unary minusR1 *multiplicationL6 /divisionL6 %moduloL6 +additionL7 − subtractionL7 * lower level == higher precedence. Level 1 has highest precedence
7
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 (16 th bit reserved for sign) adding one pushes a 1 into the sign position causes value to go negative: - 32768 7
8
Relational & Logical Operators 8 OperatorFunctionAssociativityLevel * !logical notR3 <, <=less than (equal)L9 >, >=greater than (equal)L9 ==, !=(not) equalsL10 &&logical andL14 ||logical orL15 * lower level == higher precedence. Level 1 has highest precedence
9
Relational & Logical Operators Interesting info Relational operators do not chain, > e.g., a < b < c < d will not compile associativity is irrelevant 9
10
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
11
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
12
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
13
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
14
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
15
Bitwise Operators 15 OperatorFunctionAssociativityLevel * ~bitwise NOTR3 >left (right) shiftL8 &bitwise ANDL11 ^bitwise XORL12 |bitwise ORL13 * lower level == higher precedence. Level 1 has highest precedence
16
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
17
Other Operators 17 OperatorFunctionAssociativityLevel * ()groupingL2 ++, --postfixL2 ++, --prefixR3 * Lower level == higher precedence. Level 1 has highest precedence
18
Assignment Operators 18 OperatorFunctionAssociativityLevel * =assignmentR17 +=, − =, *=, /=, %= arithmetic assignment R17 >>=, <<=, &=, |=, ^= bitwise assignmentR17 * Lower level == higher precedence. Level 1 has highest precedence
19
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
20
Questions? 20
21
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
22
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
23
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
24
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
25
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
26
Operator Overloading Operators you should define if it makes sense For use with STL < == != : to go along with == To print your class << 26
27
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 2 nd 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
28
Operator Overloading 28 ostream& operator<<(ostream& os, const Book& book){ os << book.author_ << “ “; os << book.title_ << “ “; os << book.retail_price_; }
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 classes friend class class1 e.g., friend class Song 29
30
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
31
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); };
32
Questions? 32
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.