adding the overloading example

This commit is contained in:
Jidong Xiao
2024-02-23 12:26:30 -05:00
parent e732c2738c
commit 7ab098d125
4 changed files with 101 additions and 0 deletions

View File

@@ -156,6 +156,12 @@ function of the Complex class. This is why stream operators are never member fun
- Stream operators are either ordinary non-member functions (if the operators can do their work through the
public class interface) or friend functions (if they need non public access).
You can compile and run these three examples, in which the output stream operators are overloaded as a non-member function, a friend function, and a member function.
- [Example 1](overloading_non_member.cpp)
- [Example 2](overloading_friend.cpp)
- [Example 3](overloading_member.cpp) - pay attention to the main function, does it surprise you?
## 13.10 Summary of Operator Overloading in C++
- Unary operators that can be overloaded: + - * & ~ ! ++ -- -> ->*

View File

@@ -0,0 +1,32 @@
// Overloading the output stream operator as a friend function.
#include <iostream>
class MyClass {
private:
int value;
public:
MyClass(int val) : value(val) {}
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj);
// getter function to access private member
int getValue() const {
return value;
}
};
// overload the output stream operator as a non-member function
std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "Value: " << obj.value;
return os;
}
int main() {
MyClass obj(42);
// output the object using the overloaded operator
std::cout << obj << std::endl;
return 0;
}

View File

@@ -0,0 +1,32 @@
// Overloading the output stream operator as a member function.
#include <iostream>
class MyClass {
private:
int value;
public:
MyClass(int val) : value(val) {}
// getter function to access private member
int getValue() const {
return value;
}
// overload the output stream operator as a non-member function
std::ostream& operator<<(std::ostream& os) {
os << "Value: " << value;
return os;
}
};
int main() {
MyClass obj(42);
// output the object using the overloaded operator
obj << std::cout << std::endl;
return 0;
}

View File

@@ -0,0 +1,31 @@
// Overloading the output stream operator as a non-member function.
#include <iostream>
class MyClass {
private:
int value;
public:
MyClass(int val) : value(val) {}
// getter function to access private member
int getValue() const {
return value;
}
};
// overload the output stream operator as a non-member function
std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "Value: " << obj.getValue();
return os;
}
int main() {
MyClass obj(42);
// output the object using the overloaded operator
std::cout << obj << std::endl;
return 0;
}