[资料]c 运算符重载赋值运算符
C++运算符重载赋值运算符
文章来源:PConline 作者:管宁
自定义类的赋值运算符重载函数的作用与内置赋值运算符的作用类似,但是要要注意的是,它与拷贝构造函数与析构函数一样,要注意深拷贝浅拷贝的问题,在没有深拷贝浅拷贝的情况下,如果没有指定默认的赋值运算符重载函数,那么系统将会自动提供一个赋值运算符重载函数。
赋值运算符重载函数的定义与其它运算符重载函数的定义是差不多的。
下面我们以实例说明如何使用它,代码如下: //程序作者:管宁
//站点:www.cndev-lab.com
//所有稿件均有版权,如要转载,请务必著名出处和作者
#include
using namespace std;
class Internet
{ public:
Internet(char *name,char *url)
{
Internet::name = new char[strlen(name)+1];
Internet::url = new char[strlen(url)+1];
If(name)
{
strcpy(Internet::name,name);
}
if(url)
{
strcpy(Internet::url,url);
}
}
Internet(Internet &temp)
{
Internet::name=new char[strlen(temp.name)+1];
Internet::url=new char[strlen(temp.url)+1];
if(name)
{
strcpy(Internet::name,temp.name);
}
if(url)
{
strcpy(Internet::url,temp.url);
}
}
~Internet()
{
delete[] name;
delete[] 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)
{
strcpy(this->name,temp.name);
}
if(this->url)
{
strcpy(this->url,temp.url);
}
return *this;
}
public:
char *name;
char *url;
};
int main()
{
Internet a("中国软件开发实验室","www.cndev-lab.com");
Internet b = a; //b对象还不存在~所以调用拷贝构造函数~进行构造处理。
cout<