C++ object pointer practice

1. The topic is as follows:

 

 2. Come on, show:

Coordinate.h

class Coordinate
{
public:
   Coordinate();
   ~Coordinate();
public:
    int m_iX;
    int m_iY;
};

Coordinates.cpp

#include <iostream>
#include "Coordinate.h"
using namespace std;

Coordinate::Coordinate()
{
    cout << "Coordinate" << endl;
}

Coordinate::~Coordinate()
{
    cout << "~Coordinate" << endl;
}

demo.cpp

#include <iostream>
#include "Coordinate.h"
#include <stdlib.h>
using namespace std;

int main(void)
{
    //从堆中实例化
    Coordinate *p1 = NULL;
    p1 = new Coordinate;
    Coordinate *p2 = new Coordinate();
    p1->m_iX = 10;
    p1->m_iY = 20;
    (*p2).m_iX = 30;
    (*p2).m_iY = 40;
    cout << p1->m_iX + (*p2).m_iX << endl;
    cout << p1->m_iY + (*p2).m_iY << endl;
    delete p1;
    p1 = NULL;
    delete p2;
    p2 = NULL;

    system("pause");
    return 0;
}

3. The running results are as follows:

 

 4. Note that we instantiate objects from the heap and need to be destroyed last

5.//Instantiate from the stack

//Operate p1 through p2

//从栈中实例化
    Coordinate p1;
    //通过p2操作p1
    Coordinate *p2 = &p1;

    p2->m_iX = 10;
    p2->m_iY = 20;
    (*p2).m_iX = 10;

    cout << p1.m_iX << endl;
    cout << p1.m_iY << endl;

6. The running results are as follows:

I hope I can help everyone, I ask you if you want a like, will you give it, thank you all.
Copyright statement: The copyright of this article belongs to the author (@攻城狮小关) and CSDN. Welcome to reprint, but you must keep this paragraph without the author’s consent Statement, and provide the original link in an obvious place on the article page, otherwise the right to pursue legal responsibility is reserved.
It is not easy for everyone to write articles, please respect the fruits of labor~ 
Communication plus Q: 1909561302
Blog Park Address https://www.cnblogs.com/guanguan-com/

 

Guess you like

Origin blog.csdn.net/Mumaren6/article/details/108959292