#include<iostream>
#include<string.h>
#include<windows.h>
using namespace
std;
class stringy
{
friend
ostream &operator<<(ostream&, stringy&); /*friend
means two classes can access the private data members of each other. This is
considered by many bad programming practice, but we need to use it.*/
public:
stringy(char*
= "temp"); /*char pointers must always have
a value, so do this to be safe*/
stringy operator+(stringy&);
/*adds 2 strings (see details later in program) */
void
sets(); /*sets a value for the pointer str*/
private:
char *str;
};
stringy::stringy(char *in)/*constructor, what do you think? */
{
str = new char[500];/*allocates a large space for the array*/
strcpy(str, in);
}
void stringy::sets()/*sets a value for the pointer str
based on what the user enters*/
{
cout<<"Enter
a string:";
cin.getline(str, 500, '\n');
}
stringy stringy::operator+(stringy &other)
/*you can think
of this like object1+object2 is the same as object1.add(object2) the first one
is the "calling" object so you use str to access
the calling string, and other.str to access the
second string (from after the +)*/
{
return
stringy(strcat(str,other.str));
/*returns a new stringy object*/
}
main()
{
stringy one;
stringy two;
one.sets();
two.sets();
cout<<flush;
/*use this or the program gives you a run-time error,
don't ask why*/
stringy three=one+two;
/*assigns one plus two to three*/
cout<<three;
/*prints three.str, see the
overloaded operator below*/
return
0;
}
ostream &operator<<(ostream
&screen, stringy &brandnew)
/*all ostream operators return an ostream&
They all also accept one ostream&
and whatever else you want or need it to, int this
case a stringy reference (stringy&)*/
{
screen<<brandnew.str<<endl; /*this is what <<(object_name) will print in a cout*/
return
screen; /*return it so that you ca use cout<<other stuff<<(object_name)<<other
stuff; */
}
