zoukankan      html  css  js  c++  java
  • 【C++ Primer 第13章】3. 交换操作

    交换操作

     1 class HasPtr {
     2     friend void swap(HasPtr &rhs, HasPtr &yhs);
     3     //其他成员定义
     4 };
     5 
     6 void swap(HasPtr &rhs, HasPtr &yhs)
     7 {
     8     using std::swap;
     9     swap(rhs.ps, yhs.ps); //交换指针,而不是string 
    10     swap(rhs.i, yhs.i);   //交换int成员
    11 }

    在赋值运算符中使用swap

    1 // 注意rhs是按值传递的。意味着HasPtr的拷贝构造函数
    2 // 将右侧运算对象中的string拷贝到rhs
    3 HasPtr& HasPtr::operator=(HasPtr rhs)
    4 {
    5     swap(*this, rhs);
    6     return *this;
    7 }

    13.3节练习

    • 13.30

     1 #include<iostream>
     2 #include<string>
     3 using namespace std;
     4 
     5 class HasPtr {
     6     friend void swap(HasPtr &rhs, HasPtr &yhs);
     7 public:
     8     HasPtr(const string &s = string()): ps(new string(s)), i(0) {}
     9     HasPtr(const HasPtr &rhs): ps(new string(*rhs.ps)), i(rhs.i) {}
    10     ~HasPtr();
    11 
    12     HasPtr& operator=(const HasPtr &rhs);
    13     HasPtr& operator=(const string &rhs);
    14     string& operator*();
    15 private:
    16     string * ps;
    17     int i;
    18 };
    19 
    20 HasPtr::~HasPtr()
    21 {
    22     delete ps;
    23 }
    24 
    25 HasPtr& HasPtr::operator=(const HasPtr &rhs)
    26 {
    27     auto newp = new string(*rhs.ps);
    28     delete ps;
    29     ps = newp;
    30     i = rhs.i;
    31     return *this;
    32 }
    33 
    34 HasPtr& HasPtr::operator=(const string &rhs)
    35 {
    36     *ps = rhs;
    37     return *this;
    38 }
    39 
    40 string& HasPtr::operator*()
    41 {
    42     return *ps;
    43 }
    44 
    45 void swap(HasPtr &rhs, HasPtr &yhs)
    46 {
    47     cout << "交换" << *rhs.ps << "" << *yhs.ps << endl;
    48     using std::swap;
    49     swap(rhs.ps, yhs.ps);
    50     swap(rhs.i, yhs.i);
    51 }
    52 
    53 int main()
    54 {
    55     HasPtr h("hi, mom!");
    56     HasPtr h2 = h;
    57     HasPtr h3 = h;
    58     h2 = "hi, dad!";
    59     h3 = "hi, friend";
    60     cout << "h2: " << *h2 << endl;
    61     cout << "h3: " << *h3 << endl;
    62     swap(h2, h3);
    63     cout << "h2: " << *h2 << endl;
    64     cout << "h3: " << *h3 << endl;
    65     return 0;
    66 }

    运行结果:

  • 相关阅读:
    java中JSON转换
    使用Admin监控
    linux安装tomcat
    SpringBoot整合Redis
    linux6.8安装docker
    使用Actuator监控
    SpringBoot集成阿里巴巴Druid监控
    使用Log4j日志处理
    SpringBoot多数据源
    SpringBoot文件上传下载
  • 原文地址:https://www.cnblogs.com/sunbines/p/9006494.html
Copyright © 2011-2022 走看看