#include <iostream>
#include <cstring>
using namespace std;
class MyString{
private:
char *p_string;
int str_length;
public:
MyString(char *origin);
~MyString(){
if(p_string != NULL){
delete []p_string;
cout<< "析构函数被调用"<< endl;
}
}
char* getP_string(){
return p_string;
}
void print_Add(){
cout<< &p_string<< endl;
}
void set_p(char* origin){
int l = strlen(origin);
if(l <= strlen(p_string)){
p_string = origin;
}else{
str_length = l;
delete []p_string;
p_string = new char[l + 1];
strcpy(p_string, origin);
}
}
};
MyString::MyString(char *origin){
str_length = strlen(origin);
p_string = new char[str_length + 1];
strcpy(p_string, origin);
p_string[str_length] = '\0';
cout<< "构造函数被调用"<< endl;
//cout<< &p_string<< endl;
}
int main(){
MyString iteral("iteral");
MyString copy(iteral);
copy.set_p("Hello");
cout<< iteral.getP_string()<< endl;
cout<< copy.getP_string()<< endl;
return 0;
}
上面这段代码,为什么在执行时,加入了析构函就报错?还有就是为什么我没写深拷贝构造函数,为什么两个对象中的指针分别指向的是不同的内存?