C++之对象实例化,以从栈或从堆实例化赋值x和y为例

1.题目要求:从栈或从堆实例化对x和y进行任意赋值

2.代码如下:

#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.运行如下:

 4.虽然写这么多代码,只为了给x和y赋值,但是可以清晰看出从栈或堆实例化对象的区别

希望能帮到大家,问你们要一个赞,你们会给吗,谢谢大家
版权声明:本文版权归作者(@攻城狮小关)和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
大家写文都不容易,请尊重劳动成果~
交流加Q:1909561302
CSDN地址https://blog.csdn.net/Mumaren6/

原文地址:https://www.cnblogs.com/guanguan-com/p/13652354.html