I made a class str
for practice, and I use operator =
to
assign an object into another.
I make like this.
#include <string.h>
class Str{
private:
char *str;
int len;
int num;
public:
Str(int leng);
Str(char *neyong);
~Str();
int length(void);
char *contents(void);
int compare(Str a);
int compare(char *a);
void operator=(char *a);
void operator=(Str a);
};
Str::Str(char *neyong){
len = strlen(neyong);
str = new char[len + 1];
strcpy(str, neyong);
}
Str::~Str(){
delete[] str;
}
int Str::length(void){
return len;
}
char* Str::contents(void){
return str;
}
void Str::operator=(Str a){
len = a.length();
str = new char[len+1];
strcpy(str, a.contents());
}
(I skip some functions for ease of reading)
And I execute this like below code.
Str a("hahahaha"), b("hihihihihihi");
cout << a.contents() << endl;
cout << b.contents() << endl;
a = b;
cout << b.contents() << endl;
cout << a.contents() << endl;
Problem: When I assign a = b
, then destructors of b is
automatically called. Probably b.~Str()
erases all its content and hence b.contents()
doesn't return proper value.
How can I solve this problem????