注册 登录
编程论坛 C++教室

关于引用T-T

bid2938692 发布于 2010-04-24 19:44, 320 次点击
#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)中的两个&去掉呢,如果去掉一个会怎么样呢,可以说明下吗??


[ 本帖最后由 bid2938692 于 2010-4-24 21:26 编辑 ]
1 回复
#2
南国利剑2010-04-25 16:43
不能去掉,
你要做的是重载运算符=
使它具有对类namelist进行操作的功能,
所以,如果不是用引用的话,那么就要重新构造新的对象,
构造的时间分别在函数被调用时,和return语句处。

函数调用时构造对象只是浪费了内存,
而函数返回时构造新对象就使赋值号失去了重载的意义了,
或者说你要在重载函数中实现的一些特殊功能也就不能实现了。

而如果用引用的话,上述问题都不存在了,因为,他们使用的都是原有的对象。
只是取了一个别名罢了。

1