重载=操作符

Overloading the = operator

本文关键字:操作符 重载      更新时间:2023-10-16

我正在为我所做的类重载operator=。我在两堂课上都这样做了,其中一节课运行得很好,看起来都做得很正确。其中一个重载操作符不工作。该程序不会生成任何错误,它只是简单地返回类的空白版本。如果有人有任何想法,什么可能是问题,这将是非常感激。

. h文件
Patient operator=(const Patient &right);

. cpp文件
 //Overloaded functions
Patient Patient::operator=(const Patient &right)
{
    Patient temp;
    temp.patientName = right.patientName;
    temp.age = right.age;
    temp.code = right.code;
    temp.problem = right.problem;
    temp.doctorName = right.doctorName;
    temp.roomNum = right.roomNum;
    temp.isWaiting = right.isWaiting;
    temp.isComplete = right.isComplete;
    return temp;
}

正在使用的程序的一部分。我知道随机输出消息,我试图找到我在程序中遇到问题的地方。缩小到pat=p;语句

void Room::setPat(Patient p)
{   
    cout << "Test" << endl;
    cout << p.getName() << pat.getName() << "end";
    pat = p;
    cout << p.getName() << pat.getName() << "end";
    cout << "End Test" << endl;
    patUsed = true;
 }  

从您提供的代码判断,不需要编写赋值操作符。编译器生成的一个就可以了。

您不需要"tmp."把它删掉。并返回一个引用。

Patient& Patient::operator=(const Patient &right)
{
patientName = right.patientName;
age = right.age;
code = right.code;
problem = right.problem;
doctorName = right.doctorName;
roomNum = right.roomNum;
isWaiting = right.isWaiting;
isComplete = right.isComplete;
return *this;
}

你的原始代码没有修改=的左操作数,结果不是预期的。

如果你的Patient没有其他成员,这个=()定义是不必要的,你可以省略它。编译器将为您生成它,并对每个成员进行"简单"赋值,如pointing @sellibitze。只有在需要其他东西(例如深度复制)时才定义自己的=()。我希望你在这里没有复制任何指针,并且每个成员的类都有一个"正确的"= () self。

1)不需要在赋值操作符内创建任何temp

2)赋值操作符应该返回对自身的引用。

例子。

     //Overloaded functions
    Patient& Patient::operator=(const Patient &right)
    {
    patientName = right.patientName;
    age = right.age;
    code = right.code;
    problem = right.problem;
    doctorName = right.doctorName;
    roomNum = right.roomNum;
    isWaiting = right.isWaiting;
    isComplete = right.isComplete;
    return *this;
    }

问题是你没有设置当前对象的任何值,而只是创建一个新对象并返回它。

Patient& Patient::operator=(const Patient &right)
{
    patientName = right.patientName;
    age = right.age;
    code = right.code;
    problem = right.problem;
    doctorName = right.doctorName;
    roomNum = right.roomNum;
    isWaiting = right.isWaiting;
    isComplete = right.isComplete;
    return *this;
}

请注意,局部变量已被删除,而您正在将类变量和引用赋值给当前类。