constructors, copy constructors, assignment operators

Source: Internet
Author: User

For the relationship between such a class and class, we want to write a "deep copy" for it. The two classes are defined as follows:

class Point {    int  x;     int y;}; class  Public Shape {    *points;};

1. Constructors

// constructor Function  Polygon (const point &p): _point (new point ) {  this->_point->x = p.x;  This->_point->y = p.y;}

2. Copy Constructors

// Copy Construction Polygon (const Polygon &p): _point (new point ) {    this->_ Point->x = p._point->x;     This->_point->y = p._point->y;}

3. Assignment constructors

// assignment operator void operator= (const Polygon &rhs) {    this->_point->x = rhs._point-> x;     This->_point->y = rhs._point->y;}

  All Code & Test Cases

#include <iostream>using namespacestd;structShape {intNo//Shape Number};structPoint {intx; inty; Point (intXinty): x (x), Y (y) {} point ()=default;};structPolygon: PublicShape { point*_point; //constructor FunctionPolygon (ConstPoint &p): _point (NewPoint ) {         This->_point->x =p.x;  This->_point->y =p.y; }    //Copy ConstructionPolygon (ConstPolygon &p): _point (NewPoint ) {         This->_point->x = p._point->x;  This->_point->y = p._point->y; }    //assignment operator    void operator= (ConstPolygon &RHS) {         This->_point->x = rhs._point->x;  This->_point->y = rhs._point->y; }    ~Polygon () {Delete  This-_point; }};intMain () {Point X1 (1,2);    Polygon p1 (x1); Polygon P2=P1;    Polygon P3 (p2); P1=P2; return 0;}
View Code

  In-memory variable address

P1. _ponit memory Address 0x002c0cb8

P2. _point memory Address 0x002c0cf0

P3. _point memory Address 0X002C0D28

(All memory addresses are not the same)

Success

constructors, copy constructors, assignment operators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.