1 / 13

Operator Overloading. CSCE 121 J. Michael Moore. Based on Slides created by Carlos Soto. Operators. Assignment: = Arithmetic: +, -, *, /, % Compound assignment: +=, -=, *=, /=, %= Increment/decrement: ++, -- Logical: !, &amp;&amp;, || Comparison: ==, !=, &lt;, &gt;, &lt;=, &gt;= Other: &lt;&lt;, &gt;&gt;, etc.

Télécharger la présentation

E N D

### Presentation Transcript

1. Operator Overloading CSCE 121 J. Michael Moore Based on Slides created by Carlos Soto.

2. Operators Assignment: = Arithmetic: +, -, *, /, % Compound assignment: +=, -=, *=, /=, %= Increment/decrement: ++, -- Logical: !, &&, || Comparison: ==, !=, <, >, <=, >= Other: <<, >>, etc.

3. Operators (kind of like functions...) int a = 0, b = 5; int c = a + b; // int +(int a, int b); c++; // void ++(int& c); int d = a; // void =(constint& a, int &d);

4. Operators (a lot like functions...) inti = 0, j = 5; string s; i++; // matches ++ operator’s ‘arguments’ s++;// no match int k = i + j;// integer addition string s2 = s + s;// string concatenation

5. Operator Overloading int k = i + j; // int +(int a, int b); string s2 = s + s; // string +(string a, string b); NOT actually a function, because int is a PRIMITIVE datatype

6. Operator Overloading int k = i + j; // int +(int a, int b); string s2 = s + s; // string operator+(const& string a, const& string b);

7. Operator overloading class MyClass { intmyAttr= 7; }; // outside class scope MyClass operator+(constMyClass& a, constMyClass& b) { // ... } Does not have access to private MyClass data and methods.

8. Operator overloading (inside class scope) class MyClass { intmyAttr = 7; // ... public: // ... MyClass(int k) : myAttr(k) {} MyClass operator==(constMyClass& b) { // ... } }; MyClass operator+(constMyClass& a, constMyClass& b); Has access to private MyClass data and methods

9. Parameters (implicit and explicit) bool MyClass::operator==(constMyClass& other){ return (myAttr == other.myAttr); } // ... MyClass a = MyClass(7); MyClassB = MyClass(11); if (a == b) { // ... } Equivalent to calling: if (a.operator==(b)) {

10. Alternatively bool MyClass::operator==(constMyClass& other){ return (this->myAttr== other.myAttr); } element access operator for pointers to objects Recall:: ‘this’ is a pointer to the instance of the class Student that called the == operator

11. Return types string operator+(const string& a, const string& b); bool MyClass::operator==(constMyClass& other); MyClass& MyClass::operator=(constMyClass & other);

12. Returning a reference in a overloaded operator MyClass& MyClass::operator=(constMyClass& other) { this->myAttr = other.myAttr; return *this; } Essentially, dereference ‘this’ and the compiler knows how to get the address from the class.

13. Rules for Operator Overloading • Can only overload existing operators • can’t create your own • Cannot change the number of operands • Must take at least one non-primitive datatype operand

More Related