Member Operator Function

Here is another simple example of operator overloading through a member operator function. In the following program, a class Sentence which has a string member variable is defined. Sentence overloads the + operator in order to allow two sentences to be concatenated with a space in between them. It also overloads = and ++. The latter will add a space at the end of the sentence it is applied to.

Example


#include <iostream>
#include <string>

using namespace std;

class Sentence
{
     string sent;
public:
     Sentence() {}

     Sentence(string s)
     {
           sent = s;
     }

     void printSentence()
     {
           cout << sent;
     }

     Sentence operator+(Sentence secondOperand) // concatenates
     {
           Sentence temp("");
           temp.sent = sent + " " + secondOperand.sent;
           return temp;
     }

     Sentence operator=(Sentence secondOperand) // unnecessary as
 // the standard "=" does just the same
     {
           sent = secondOperand.sent;
           return *this;
     }

     Sentence operator++() // this is the prefix version. For
                           // the postfix: operator++(int x),
     {                     // called with x=0.
           sent = sent + " ";
           return *this;
     }
};

int main()
{
     Sentence s1("Hi");
     Sentence s2("there!");
     Sentence s3;
     s3 = s1 + s2 + s1;
     s3.printSentence();
     cout << "\n";
     ++s3;
     ++s3;
     ++s3;
     s1.printSentence();
     cout << "\n";
     s3 = s3 + s1;
     s3.printSentence();
}

Output

Hi there! Hi
Hi
Hi there! Hi    Hi