注册 登录
编程论坛 C++ Builder

关于引用T-T

bid2938692 发布于 2010-04-24 19:46, 715 次点击
#include <iostream>
using namespace std;
#include <cstring>
class Namelist
{    char *name;
    public:
        Namelist(char *p)
        {    name=new char[strlen(p)+1];
            if(name!=0)strcpy(name,p);
        }
        ~Namelist()
        {    delete[] name;
        }
        Namelist& operator=(char *p);
        Namelist& operator=(Namelist&);
        void display(){cout<<name<<endl;}
};
Namelist& Namelist::operator=(char *p)
{    name=new char[strlen(p)+1];
    if(name!=0)strcpy(name,p);
    return *this;
}
Namelist& Namelist::operator=(Namelist& a)
{    if(this!=&a)
    {    delete name;
        name=new char[strlen(a.name)+1];
        if(name!=0)strcpy(name,a.name);
    }
    return *this;
}
int main()
{    Namelist n1("rO"),n2("lo");
    cout<<"赋值前的数据:"<<endl;
    n1.display();
    n2.display();
    cout<<"赋值后的数据:"<<endl;
    n2=n1;
    n1.display();
    n2.display();
    return 0;
}
为什么不能把Namelist& Namelist::operator=(Namelist& a)中的两个&去掉呢,如果去掉一个会怎么样呢,可以说明下吗??
0 回复
1