Using class String -concatenate two names by operator overloading operator +
class String data members : name,length members functions : constructors ,print,additon
function
#include <iostream>
#include <string.h>
using namespace std;
//Class string for implementing operator overloading to concatenate two strings
class String {
public:
// Name member
char name[70];
// Default constructor
String() {}
//Parameterized constructor
String(char name[])
{
strcpy(this->name, name);
}
//Print function to display results of concatenated string
void print()
{
cout<<name;
}
String addition(String s1, String s2, String s3)
{
s3 = s1 + s2;
}
// Overload Operator+ to concatenate the strings
String operator+(String& s2)
{
String s3;
// Use strcat() to concatenate two specified string
strcat(this->name, s2.name);
// Copy the string to string to be return
strcpy(s3.name, this->name);
// return the object
return s3;
}
};
//Main function
int main()
{
//Declare and initialize two strings
char str1[] = "Hello";
char str2[] = "World";
// Declaring and initializing the class
// with above two strings
String s1(str1);
String s2(str2);
String s3;
// Concatenate the strings
s3 = s1 + s2;
//Display concatenated string
s1.print();
return 0;
}
Comments
Leave a comment