重载赋值运算符(operator =)及swap

1. operator= 返回一个reference to *this, 即重载赋值运算符时要返回*this对象的引用

2. 在operator =中处理“自我赋值”, 即重载赋值运算符时要尽量考虑当传递的参数是自身对象时的情况, eg:

if(this = &meb)
   return *this

3. swap操作

(1) 容器类的swap函数: vector.swap(meb)

不会删除原始数据也不会申请新的空间, 且迭代器也不会失效(我的理解是只是交换读取数据的指针位置),所以速度会很快

(2) 泛型算法的swap函数: std:swap(meb1,meb2)

例:
String& operator=(String rhs) // yes, pass-by-value
{
     swap(rhs);
     return *this;
}
void swap(String& rhs)
{
    std::swap(data_, rhs.data_);
}
(a) String &, 返回*this对象的引用
(b) String rhs, 使用值传递而不使用引用的方式传递参数的是由于之后会使用swap函数, 那么this->data_会窃取rhs.data_的资源,反之rhs.data_也是, 但由于this->data_并没有申请空间, 所以此时rhs.data_指向了空, 破坏了传进来的数据. 而使用值传递方式, 会创建一个临时对象, 而this->data_是窃取的临时对象的资源, 而临时对象本来重载函数调用之后就会回收,所以也没有其他影响.
(3) 如果rhs是this对象本身,也不要紧, 因为传进来跟不是this对象, 而是拷贝this对象的临时对象.



Reference

[1] 《Effective C++》学习笔记条款10 令operator= 返回一个reference to *this
[2]  C++面试中string类的一种正确写法



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,根据你的要求,我为你编写了如下的学生类,并重载赋值运算符“=”和输入输出运算符“<<”和“>>”: ```c++ #include <iostream> #include <string> using namespace std; enum Sex { Male, Female }; // 定义枚举类型Sex表示性别 class Student { public: Student() = default; // 默认构造函数 Student(int num, string name, Sex sex, float score) : number(num), name(name), sex(sex), score(score) {} // 带参构造函数 // 重载赋值运算符"=" Student& operator=(const int& num) { number = num; return *this; } Student& operator=(const string& n) { name = n; return *this; } Student& operator=(const float& s) { score = s; return *this; } // 重载输入输出运算符">>"和"<<" friend istream& operator>>(istream& in, Student& s) { in >> s.number >> s.name >> s.sex >> s.score; return in; } friend ostream& operator<<(ostream& out, const Student& s) { out << s.number << " " << s.name << " " << s.sex << " " << s.score << endl; return out; } private: int number; string name; Sex sex; float score; }; int main() { Student s; int num = 1001; string name = "Tom"; float score = 89.5; s = num; s = name; s = score; cout << "请输入学生的学号、姓名、性别和分数:" << endl; cin >> s; cout << "学生信息如下:" << endl; cout << s; return 0; } ``` 在上面的代码中,我们定义了一个类 `Student`,它包含了学号、姓名、性别和分数等数据成员,并定义了一个对象 `s`。在 `Student` 类中,我们重载赋值运算符“=”和输入输出运算符“<<”和“>>”,使得我们可以通过直接赋值或者输入输出来操作学生类的对象。 在 `main` 函数中,我们首先定义了一个学生对象 `s`,并通过重载赋值运算符“=”,分别将整型、字符串和浮点型的数据赋值给了该对象。接着,我们通过重载的输入运算符“>>”从标准输入中输入学生的各项信息,并通过重载的输出运算符“<<”将学生的信息输出到标准输出中。 希望这个示例可以帮助你理解如何定义学生类,并重载赋值运算符“=”和输入输出运算符“<<”和“>>”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值