I can't figure out what's wrong with my + function. 'my_string temp' doesn't appear to be assigning a memory address to temp.s or the correct value to temp.len and so the terminates with an error. Please help.
Code:
#include <iostream>
#include <string.h>
using namespace std;
class my_string {
char *s;
int len;
public:
my_string(int n) { s = new char[n+1]; len = n; }
my_string() { len = 255; s = new char[255]; }
~my_string() { delete s; }
void assign(char* st) { strcpy(s, st); len = strlen(st); }
int length() { return (len); }
void print() { cout << s << "\nLength: " << len << "\n"; }
friend my_string operator +(my_string& a, my_string& b);
};
main()
{
char achar[] = "Yay!", bchar[] = " Coolio!";
my_string a, b, c;
a.assign(achar), b.assign(bchar);
c = a+b;
}
my_string operator +(my_string& a, my_string& b)
{
my_string temp;
temp.assign(strcpy(temp.s, a.s));
if (a.len + b.len < 255)
temp.assign(strcat(temp.s, b.s));
else
cerr << "Max length exceeded in concatenation.\n";
return (temp);
}
void print(char *c)
{
cout << c << "\nLength is " << strlen(c) << "\n";
}