Hello everyone, i have not posted here in a while. But i have a question about a string class I'm creating. Every time i make a string class this always happens, and i cannot figure out why. Maybe its something i didn't include or something i have to add. But i hope someone here will be able to answer my question.
class StRiNg
{
public:
StRiNg()
{
sTrLeN = 0;
sTr = new char[1];
sTr[0] = '\0';
}
StRiNg(char* s)
{
sTrLeN = (int)strlen(s);
sTr = new char[(sTrLeN+1)];
for(int i = 0; i < sTrLeN; i++)
sTr[i] = s[i];
sTr[sTrLeN] = '\0';
}
~StRiNg()
{
delete sTr;
sTrLeN = 0;
}
StRiNg operator=(char* s)
{
try
{
delete sTr;
sTrLeN = (int)strlen(s);
sTr = new char[(sTrLeN+1)];
for(int i = 0; i < sTrLeN; i++)
sTr[i] = s[i];
sTr[sTrLeN] = '\0';
}
catch(...)
{
return *this;
}
return *this;
}
bool operator==(char* s)
{
try
{
if((int)strlen(s) != sTrLeN)
throw 0;
bool same = true;
for(int i = 0; i < sTrLeN && same; i++)
{
if(sTr[i] != s[i])
same = false;
}
if(!same)
throw 0;
}
catch(...)
{
return false;
}
return true;
}
bool operator!=(char* s)
{
if(*this == s)
return false;
return true;
}
char operator[](int num)
{
try
{
if(num < 0 || num > sTrLeN)
throw 0;
return sTr[num];
}
catch(...)
{
return '\0';
}
return '\0';
}
char* GetString() { return sTr; }
int GetLength() { return sTrLeN; }
protected:
char* sTr;
int sTrLeN;
};
That is the base of my class, of course i will add other functions.. but here is my problem:
int main()
{
StRiNg s1 = "Hello";
StRiNg s2 = "How are you?";
cout << s1.GetString() << endl; // works fine
cout << s2.GetString() << endl; // works fine
// Here is where the problem starts:
s1 = s2.GetString();
cout << s1.GetString() << endl; // should be How are you but it is far from that, i get random characters...
return 0;
}
I would have added an = operator for other strings but if it doesn't even work this way, i don't know whats wrong.
And last: if anyone knows, is there a way i could do like cout << s1 << endl; without having to put the .GetString() like make a default return value for the StRiNg or overload cout to allow that?
Thanks a lot for any help anyone might give me. (even if i don't get any XD)