Overloading of Relational Operators


#include <iostream.h>
#include <string.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class string
{
        char *s;
        int length;
    public:
        string();
        string(char*);

        // Overloaded Relational operator '=='
        int operator == (string);
        // Overloded '+' operator
        friend string operator + (string, string);

        void show();
};
string::string()
{
    length = 0;
    s = new char[length + 1];
    s[0] = '\0';     // empty string
}
string::string(char *str)
{
    length = strlen(str);
    s = new char[length + 1];
    strcpy(s,str);
}
// Overloaded '==' relational operator as a member function
int string::operator == (string x)
{
    int flag = 0;
    if (length == x.length)
    {
        flag = 1;
        for (int i=0; i<length; i++)
        {
            if (s[i] != x.s[i])
            {
                flag = 0;
                break;
            }
        }
    }
    return flag;
}
void string::show()
{
    cout << s << "\t(Length = " << length << ")\n";
}
/*----------------------Definition ends here---------------------*/
// Overloded '+' (concatenation) operator as a friend function
string operator + (string x, string y)
{
    string temp;
    temp.length = x.length + y.length;
    temp.s = new char[temp.length + 1];
    strcpy(temp.s, x.s);
    strcat(temp.s, y.s);
    return temp;
}
void main(void)
{
    string s1("Good "),s2("Morning"),s3, s4("Morning");
    clrscr();
    s3 = s1 + s2; // concatenation
    cout << "The result of concatenation :\n";
    s3.show();

    cout << "\nThe result of comparison of s1 & s2 :\n";
    cout << (s1 == s2);
    cout << "\nThe result of comparison of s2 & s4 :\n";
    cout << (s2 == s4);
    getch();
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|