Answer to Question #156467 in C++ for Ansil Rahim

Question #156467

Using class String -concatenate two names by operator overloading operator +

class String data members : name,length members functions : constructors ,print,additon 

function


1
Expert's answer
2021-01-19T01:57:17-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog