I'm studying C++, I ran these codes in Visual Studio, but I got an access violation exception, VS told me the exception happened at line:24, in strcat() in func
mystring& operator+(mystring& z)
. Could you please help me find out the reason?
#include <iostream>
#include <string.h>
#pragma warning(disable:4996)
using namespace std;
class mystring
{
private:
char* p;
int i;
public:
mystring(char* ps)
{
p = ps;
i = strlen(ps) + 1;
}
mystring& operator+(char* s)
{
strcat(p, s);
return *this;
}
mystring& operator+(mystring& z)
{
strcat(p, z.p);
return *this;
}
friend mystring& operator+(char* d, mystring& s)
{
strcat(s.p, d);
return s;
}
void print()
{
cout << this->p;
}
};
int main()
{
char t[300] = "def", i[100] = "abc";
mystring t1(i);
t1 = t1 + t;
t1.print();
mystring s2(i);
t1 = t1 + s2;
t1.print();
mystring s3(i);
t1 = i + s3;
t1.print();
return 0;
}