C++ 重载=运算符

C++ 重载=运算符,c++,class,header,operator-overloading,implementation,C++,Class,Header,Operator Overloading,Implementation,我正在为我创建的类重载操作符=。我为两个班做了这个,其中一个班做得很好,而且两个班都做得很好。其中一个重载运算符不工作。程序没有生成任何错误,只是返回类的空白版本很简单。如果有人对可能出现的问题有任何想法,我们将不胜感激 .h文件 Patient operator=(const Patient &right); .cpp文件 //重载函数 患者患者::操作员=(常量患者和右侧) { 病人体温; temp.patientName=right.patientName; temp.age=r

我正在为我创建的类重载
操作符=
。我为两个班做了这个,其中一个班做得很好,而且两个班都做得很好。其中一个重载运算符不工作。程序没有生成任何错误,只是返回类的空白版本很简单。如果有人对可能出现的问题有任何想法,我们将不胜感激

.h文件

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

//重载函数
患者患者::操作员=(常量患者和右侧)
{
病人体温;
temp.patientName=right.patientName;
temp.age=right.age;
temp.code=右.code;
临时问题=正确的问题;
temp.doctorName=right.doctorName;
temp.roomNum=right.roomNum;
temp.isWaiting=right.isWaiting;
temp.isComplete=right.isComplete;
返回温度;
}
它正在被用于的程序的一部分。我知道随机输出的消息,我试图找到我在程序中遇到问题的地方。将其缩小到
pat=p语句

void Room::setPat(患者p)
{   
不能您不需要“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;
}
原始代码不修改
=
的左操作数,结果不是预期的结果

如果您的
患者
没有其他成员,则此
=
()定义是不必要的,您可以忽略它。编译器将为您生成它,并对每个成员进行“简单”赋值,如@sellibitze所述。您可以定义onw
=
()仅当您需要其他内容时,例如深度副本。我希望您没有在此处复制任何指针,并且每个成员的类都有一个“正确的”
=
()self。

1)您不需要在赋值运算符中创建任何临时值

2) 赋值运算符应返回对其自身的引用

例如


问题在于,您没有设置当前对象的任何值,而只是创建一个新值并返回该值

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;
}

请注意,局部变量已被删除,而您正在为当前类分配类变量和引用。

根据您提供的代码判断,无需编写赋值运算符。编译器生成的赋值运算符就可以了。

您知道op=应该更改“this”对象,不是临时的吗?谢谢你以笑声开始我的一天。
:)
除了form@plasmah说,我认为你也在做其他的作业。你需要
p=pat;
这是
p.operator=(pat)
如果您只是复制成员,请不要提供您自己的复制操作。成员复制是编译器生成的操作无论如何都会做的。我是眯着眼睛还是这只是从问题中粘贴的同一个代码?!+1。我要补充的是,这样的操作符实际上根本没有必要,因为编译器生成的操作符执行相同的操作ing(会员复制)。@Plasmah我写道“你不需要“tmp”。只要删除它。”这就是我所做的:-),但它必须是足够的。@sellibitze.Edited。谢谢。
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;
}