c++类中的函数this指针问题?
voidcopy(Personconst&rp){delete[]name;name=newchar[strlen(this->name)+1];if(name!=0)s...
void copy(Person const &rp){
delete [] name;
name=new char[strlen(this->name)+1];
if(name!=0) strcpy(name,this->name);
id = this->id;
}
这是我写的类中的一个函数,当这样引用的时候int main(){
Person p1("Randy", 1),p2;
p2.copy(p1);
p2.print();
p2.copy(p2);//主要是这里出现问题;
p2.print();
}
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
class Person{
char *name; int id;
public:
Person(const char* pn="noName", int i = 0){
name=new char[strlen(pn)+1];
if(name!=0) strcpy(name,pn);
id = i;
}
~Person(){
cout<<"Destruct "<<name<<endl;
delete [] name;
}
void print(){
cout<<name<<" : "<<id<<'\n';
}
void copy(Person const &rp){
delete [] name;
name=new char[strlen(this->name)+1];
if(name!=0) strcpy(name,this->name);
id = this->id;
}
};
int main(){
Person p1("Randy", 1),p2;
p2.copy(p1);
p2.print();
p2.copy(p2);
p2.print();
} 展开
delete [] name;
name=new char[strlen(this->name)+1];
if(name!=0) strcpy(name,this->name);
id = this->id;
}
这是我写的类中的一个函数,当这样引用的时候int main(){
Person p1("Randy", 1),p2;
p2.copy(p1);
p2.print();
p2.copy(p2);//主要是这里出现问题;
p2.print();
}
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
class Person{
char *name; int id;
public:
Person(const char* pn="noName", int i = 0){
name=new char[strlen(pn)+1];
if(name!=0) strcpy(name,pn);
id = i;
}
~Person(){
cout<<"Destruct "<<name<<endl;
delete [] name;
}
void print(){
cout<<name<<" : "<<id<<'\n';
}
void copy(Person const &rp){
delete [] name;
name=new char[strlen(this->name)+1];
if(name!=0) strcpy(name,this->name);
id = this->id;
}
};
int main(){
Person p1("Randy", 1),p2;
p2.copy(p1);
p2.print();
p2.copy(p2);
p2.print();
} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询