Inê*_*nês 5 c++ const operator-overloading operators conversion-operator
我想知道你们是否可以帮助我.
这是我的.h:
Class Doctor {
const string name;
public:
Doctor();
Doctor(string name);
Doctor & Doctor::operator=(const Doctor &doc);
}
Run Code Online (Sandbox Code Playgroud)
我的主要人物:
int main(){
Doctor d1 = Doctor("peter");
Doctor d2 = Doctor();
d2 = d1;
}
Run Code Online (Sandbox Code Playgroud)
我想做operator = function.谁能帮我?请注意Doctor上的const成员.
************编辑:*********我的主要问题是我希望另一个类有一个属性,就像一个医生,像一个Pacient有一个医生.但我希望能够改变我的医生.就像我看到医生A,但我想看医生B.这将在我的其他课程(Pacient)中使用setDoctor函数完成.如果是我在做代码我会说这样的话:
class Patient{
Doctor &d;
};
Run Code Online (Sandbox Code Playgroud)
然后更改指针.但是我正在使用由其中一位老师制作的基本代码,它的类定义如下:
class Patient{
Doctor d;
}
Run Code Online (Sandbox Code Playgroud)
但我认为这是不可能的,因为在Patient类中使用setDoctor()我会复制或改变varable本身.第一个没有任何区别,第二个是不可能的,因为const.我对吗?
你快到了.几点值得注意的几点:
该名称不应该是const
合格的.A const
无法修改,这正是我们在赋值运算符中想要的.
C++关键字是,class
而不是Class
你的代码有它(它会给你编译错误)
正如Michael Burr所指出的那样:"应该注意的是,如果类只包含已经正确支持赋值的其他类(在本例中使用简单的字符串成员),隐式的,编译器生成的operator =()将会正常工作".在这种情况下,唯一的成员string
是正确的op=
.所以明确定义是多余的.
Meeh的解决方案几乎就在那里.它唯一没有谈到的是自我分配.阅读常见问题12.
作业是三大成员函数之一FAQ 27.10.仔细看看.它说,要求实现复制ctor,op =或dtor中的任何一个通常意味着你还需要实现其他两个.
更正的代码示例应该是这样的:
class Doctor {
string name;
public:
Doctor& operator=(Doctor const& o) {
if (&o != this) name = o.name;
return *this;
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
正确定义赋值构造函数以使其异常安全的标准方法是根据复制构造函数定义它。
class Doctor
{
public:
Doctor& operator=(Doctor const& rhs)
{
if (this != &rhs)
{
Doctor tmp(rhs); // Use copy constructor here
this->swap(tmp); // Now Swap
}
return *this;
}
void swap(Doctor& rhs) throws()
{
std::swap(.....); // swap each member variable.
}
};
Run Code Online (Sandbox Code Playgroud)
通过这样做,使其异常安全。
请注意,您只需要使交换成为无抛出方法,如果您使用 STL 对象,这相对简单,因为它们都为这种情况定义了无抛出交换,boost 和所有好的库也是如此(因此您应该遵循套件)。
如果这出错了,他们将在使用复制构造函数时出错。此时您还没有修改自己的对象,因为您正在将构造复制到临时对象中。因此,您提供了良好的异常安全性,因为您的对象仍未更改。