zoukankan      html  css  js  c++  java
  • 构造函数、拷贝构造函数、赋值操作符

      对于这样一种类与类之间的关系,我们希望为其编写“深拷贝”。两个类的定义如下:

    class Point {
        int x;
        int y;
    };
    
    class Polygon : public Shape {
        Point *points;
    };

      1. 构造函数

    //构造函数
    Polygon(const Point &p) : _point(new Point)
    {
      this->_point->x = p.x;
      this->_point->y = p.y;
    }

      2. 拷贝构造函数

    //拷贝构造
    Polygon(const Polygon &p) : _point(new Point)
    {
        this->_point->x = p._point->x;
        this->_point->y = p._point->y;
    }

      3. 赋值构造函数

    //赋值操作符
    void operator= (const Polygon &rhs)
    {
        this->_point->x = rhs._point->x;
        this->_point->y = rhs._point->y;
    }

      全部代码 & 测试用例

    #include <iostream>
    
    using namespace std;
    
    struct Shape {
        int no; //形状编号
    };
    
    struct Point {
        int x;
        int y;
    
        Point(int x, int y) : x(x), y(y) {}
        Point() = default;
    };
    
    struct Polygon :public Shape {
        Point *_point;
    
        //构造函数
        Polygon(const Point &p) : _point(new Point)
        {
            this->_point->x = p.x;
            this->_point->y = p.y;
        }
    
        //拷贝构造
        Polygon(const Polygon &p) : _point(new Point)
        {
            this->_point->x = p._point->x;
            this->_point->y = p._point->y;
        }
    
        //赋值操作符
        void operator= (const Polygon &rhs)
        {
            this->_point->x = rhs._point->x;
            this->_point->y = rhs._point->y;
        }
    
        ~Polygon()
        {
            delete this->_point;
        }
    };
    
    int main()
    {
        Point x1(1, 2);
    
        Polygon p1(x1);
        Polygon p2 = p1;
        Polygon p3(p2);
    
        p1 = p2;
    
        return 0;
    }
    View Code

      内存中变量地址

     

      p1 . _ponit 内存地址 0x002c0cb8

      p2 . _point 内存地址 0x002c0cf0

      p3 . _point 内存地址 0x002c0d28

      (都是不相同的内存地址)

    成功

  • 相关阅读:
    Android 对话框(Dialog)
    struts2 开发模式
    Struts2动态方法调用(DMI)
    Struts2中 Path (getContextPath与basePath)
    String path = request.getContextPath
    ios虚拟机安装(二)
    Spring MVC 的 研发之路
    Swift辛格尔顿设计模式(SINGLETON)
    【算法导论】多项式求和
    uva 11181
  • 原文地址:https://www.cnblogs.com/fengyubo/p/5049516.html
Copyright © 2011-2022 走看看