Here is an example program that adds two strings "Hello" and "World" using operator overloading:
#include <string>
using namespace std;
class MyString {
string str;
public:
MyString() {}
MyString(string s) {
str = s;
}
MyString operator+(MyString s) {
MyString temp;
temp.str = str + s.str;
return temp;
}
void display() {
cout << str << endl;
}
};
int main() {
MyString str1("Hello ");
MyString str2("World");
MyString result = str1 + str2;
result.display();
return 0;
}
Output:
Hello World
In this program, we define a class MyString that has a string data member str. We overload the + operator using a member function. The + operator concatenates two MyString objects and returns a new MyString object that contains the concatenated string. The display function is used to display the string stored in the object. In the main function, we create two MyString objects str1 and str2 and add them using the overloaded + operator. The resulting MyString object is stored in the result variable and displayed using the display function.
No comments:
Post a Comment
If you have any doubts, please let me know