C++ object instantiation, taking the example of assigning x and y from the stack or from the heap

1. Subject requirements: arbitrary assignment of x and y from the stack or instantiation from the heap

2. The code is as follows:

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

class Coordinate
{
public:
    int x;
    int y;
    void printX()
    {
        cout << x << endl;
    }
    void printY()
    {
        cout << y << endl;
    }
};
int main(void)
{
    //从栈中实例化对象
    Coordinate coor;
    coor.x = 10;
    coor.y = 20;
    coor.printX();
    coor.printY();
    //从堆中实例化对象
    Coordinate *p = new Coordinate();
    if(NULL == p)
    {
        //failed
        return 0;
    }
    p->x = 100;
    p->y = 200;
    p->printX();
    p->printY();
    delete p;
    p = NULL;

    system("pause");
    return 0;
}

3. Run as follows:

 

 4. Although so much code is written, just to assign values ​​to x and y, but you can clearly see the difference between instantiating objects from the stack or the heap

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/108536865