zoukankan      html  css  js  c++  java
  • effective c++ 条款12 赋值对象时勿忘其每一个成员

    当我们自己为class设计 copy构造函数和copy assignment操作符时,如果我们漏掉一个成员变量时,编译器并不会友好的告诉你,当然有时候我们也是故意这样做。当我们担起“为派生类写copy 函数”时责任重大,必须也要小心的复制其base class部分 如下:

    class Customer {};
    class PriorityCustomer:public Customer{
    public :
          PriorityCustomer(const PriorityCustomer& rhs);
          PriorityCustomer& operator= (const PriorityCustomer& rhs);
    private:
        int priority;
    }
    PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs):Customer(rhs),  //调用基类的copy构造函数
    priority(rhs.priority)
    {
        
    }
    PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs)
    {
        Customer::operator=(rhs);
        priority = rhs.priority;
        return *this;
    }

    由于copy构造函数和 copy assignment 函数很相似,难免不让我们产生互相调用对方的想法,所以我们需要澄清两点:

    1.在copy assignment中调用copy构造函数是不合法的因为我们试图创建已经存在的对象。

    2.相反在copy 构造函数里调用copy assignment也是不合法的,因为我们试图给没有初始化的变量赋值。。

  • 相关阅读:
    无标题
    UVA 11987 并查集删点
    屯题 (bestcoder #62~#75)
    codeforces 293E Close Vertices 点分治+滑窗+treap
    hdu4670 Cube number on a tree 点分治
    hdu4812 D Tree 点分治
    poj2112 Boatherds 点分治
    HDU 4866 Shooting 二分+主席树
    poj1741 Tree 点分治
    关于点分治。。。
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3078634.html
Copyright © 2011-2022 走看看