[cpp] view plaincopyprint
#include
#include
using namespace std;
class Internet
{
public:
Internet(char *name,char *url)
{
this->name = new char[strlen(name)+1];
this->url = new char[strlen(url)+1];
if(name!=NULL)
{
strcpy(this->name,name);
}
if(url!=NULL)
{
strcpy(this->url,url);
}
}
Internet(Internet &temp)
{
this->name=new char[strlen(temp.name)+1];
this->url=new char[strlen(temp.url)+1];
if(this->name)
{
strcpy(this->name,temp.name);
}
if(this->url)
{
strcpy(this->url,temp.url);
}
}
~Internet()
{
delete[] this->name;
delete[] this->url;
}
Internet& operator =(Internet &temp)//赋值运算符重载函数
{
delete[] this->name;
delete[] this->url;
this->name = new char[strlen(temp.name)+1];
this->url = new char[strlen(temp.url)+1];
if(this->name!=NULL)
{
strcpy(this->name,temp.name);
}
if(this->url!=NULL)
{
strcpy(this->url,temp.url);
}
return *this;
}
public:
char *name;
char *url;
};
int main()
{
Internet a("王世晖的专栏","blog.csdn.net/shihui512");
Internet b = a;//b对象还不存在,所以调用拷贝构造函数,进行构造处理。
cout<
b = c;//b对象已经存在,所以系统选择赋值运算符重载函数处理。
cout<
/*****************************
运行结果:
王世晖的专栏
blog.csdn.net/shihui512
清水河畔外网
bbs.qshpan.com
******************************/
#include
#include
using namespace std;
class Internet
{
public:
Internet(char *name,char *url)
{
this->name = new char[strlen(name)+1];
this->url = new char[strlen(url)+1];
if(name!=NULL)
{
strcpy(this->name,name);
}
if(url!=NULL)
{
strcpy(this->url,url);
}
}
Internet(Internet &temp)
{
this->name=new char[strlen(temp.name)+1];
this->url=new char[strlen(temp.url)+1];
if(this->name)
{
strcpy(this->name,temp.name);
}
if(this->url)
{
strcpy(this->url,temp.url);
}
}
~Internet()
{
delete[] this->name;
delete[] this->url;
}
Internet& operator =(Internet &temp)//赋值运算符重载函数
{
delete[] this->name;
delete[] this->url;
this->name = new char[strlen(temp.name)+1];
this->url = new char[strlen(temp.url)+1];
if(this->name!=NULL)
{
strcpy(this->name,temp.name);
}
if(this->url!=NULL)
{
strcpy(this->url,temp.url);
}
return *this;
}
public:
char *name;
char *url;
};
int main()
{
Internet a("王世晖的专栏","blog.csdn.net/shihui512");
Internet b = a;//b对象还不存在,所以调用拷贝构造函数,进行构造处理。
cout<
b = c;//b对象已经存在,所以系统选择赋值运算符重载函数处理。
cout<
/*****************************
运行结果:
王世晖的专栏
blog.csdn.net/shihui512
清水河畔外网
bbs.qshpan.com
******************************/
the correct and safe version of the MyClass assignment operator would be this:
MyClass& MyClass::operat