Wednesday 16 August 2017

Create a class String that substitutes an overloaded += operator for the overloaded + operator in the STRPLUS program in this chapter. This operator should allow statements like s1 += s2; where s2 is added (concatenated) to s1 and the result is left in s1. The operator should also permit the results of the operation to be used in other calculations, as in s3 = s1 += s2;






SOLUTION:
#include "stdafx.h"
#include "iostream"
#include "string.h"
#include "stdlib.h"
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////
class String
{
            private:
                        enum { SZ=80 };
                        char str[SZ];
            public:
                        String()
                                    {           strcpy_s(str, "");          }
                        String( char s[ ] )
                                    {           strcpy_s(str, s);           }
                        void display() const
                                    {           cout << str <<endl;     }
                        String operator += (String ss) const;
};
//---------------------------------------------------------------------------------------String String::operator += (String ss) const
                        {
                                    String temp;
                                    if( strlen(str) + strlen(ss.str) < SZ )
                                    {
                                                strcpy_s(temp.str, str);
                                                strcat_s(temp.str, ss.str);
                                    }
                                    else
                                    {           cout << "\nString overflow";    exit(1);             }
                                    return temp;
                        }
/////////////////////////////////////////////////////////////////////////////////////////
void main()
{
            String s1 = "Merry Christmas! ", s2 = "Happy new year!", s3;
            s1.display();                 s2.display();
            s3 = s1 += s2;             s3.display();
            cout << endl;
}
OUTPUT:

0 comments: