I'm having problems with these three parts of codes, in the terms of Memory Allocations. I haven't got it yet.
Could you please point out to me what I am doing wrong and how I should go on correcting it?
1:
class MyString {
public:
MyString() : str(0) {}
MyString( char *a )
{ str = new char[strlen(a)+1]; strcpy(str,a); }
~MyString() { delete[] str; }
private:
char *str;
friend ostream& operator<<(ostream &os, const MyString &str);
};
ostream& operator<<(ostream &os, const MyString &s)
{
return os << s.str << endl;
}
int main()
{
MyString str("Mitt namn");
MyString *strp = &str;
// alot of code
delete strp;
// alot of code
}
2: Defined as above
int main()
{
MyString *str1 = new MyString("Mitt namn");
MyString str2 = *str1;
delete str1;
// alot of code
cout << str2 << endl;
}
3: Still defined as above
class MyASCII : public MyString {
public:
MyASCII( char *a) : MyString(a), ascii(0)
{
if (a==0) return;
ascii = new int[strlen(a)];
for (int i=0; i<strlen(a); i++)
ascii[i] = int(a[i]);
}
~MyASCII() { delete[] ascii; }
private:
int *ascii;
};