Created
March 7, 2023 07:38
-
-
Save iarash84/c5f6a3d1f43cc95c8be01869cdba97d5 to your computer and use it in GitHub Desktop.
operator overloading example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
class MyString { | |
public: | |
MyString() : m_data("") {} | |
MyString(const std::string& data) : m_data(data) {} | |
MyString operator+(const MyString& other) const { | |
return MyString(m_data + other.m_data); | |
} | |
friend std::ostream& operator<<(std::ostream& os, const MyString& str); | |
private: | |
std::string m_data; | |
}; | |
std::ostream& operator<<(std::ostream& os, const MyString& str) { | |
os << str.m_data; | |
return os; | |
} | |
int main() { | |
MyString str1("Hello, "); | |
MyString str2("world!"); | |
MyString result = str1 + str2; // Operator+ called | |
std::cout << result << std::endl; // Operator<< called | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment