Write a C++ program to overload ‘+’ operator to find the sum of length of two given strings.(Note: if S1 and S2 are two strings then S1+S2 should give the sum of lengths of S1 and S2).
Answers
Answer:
A C++ program to overload ‘+’ operator to find the sum of length of two given strings.
Explanation:
// C++ Program to concatenate two string
// using unary operator overloading
#include <iostream>
#include <string.h>
using namespace std;
// Class to implement operator overloading
// function for concatenating the strings
class AddString {
public:
// Classes object of string
char s1[25], s2[25];
// Parametrized Constructor
AddString(char str1[], char str2[])
{
// Initialize the string to class object
strcpy(this->s1, str1);
strcpy(this->s2, str2);
}
// Overload Operator + to concat the string
void operator+()
{
cout << "\nConcatenation: " << strcat(s1, s2);
}
};
// Driver Code
int main()
{
// Declaring two strings
char str1[] = "Hello";
char str2[] = "Shivam";
// Declaring and initializing the class
// with above two strings
AddString a1(str1, str2);
// Call operator function
+a1;
return 0;
}
Output:-
Concatenation: HelloShivam
Length: 11
Answer:
Develop a program to find length of string using operator
overloading