C++ 类的栈和堆实例化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/feikon2/article/details/54288719
#include "stdafx.h"
#include <iostream>
using namespace std;

class Coordnate
{
public:
	Coordnate();
	~Coordnate();
	int x;
	int y;
	void printX()
	{
		cout << x << endl;
	}
	void printY()
	{
		cout << y << endl;
	}

private:

};

Coordnate::Coordnate()
{
}

Coordnate::~Coordnate()
{
}

int main()
{
	// 用栈初始化
	Coordnate coor;
	coor.x = 10;
	coor.y = 20;
	coor.printX();
	coor.printY();

	// 用堆初始化
	Coordnate *p = new Coordnate();
	if (NULL == p)								// 初始化失败的话p为NULL
	{
		cout << "Init FAILED" << endl;
	}
	p->x = 100;
	p->y = 200;
	p->printX();
	p->printY();
	// 调用结束后要删除,同时要把p重新赋值为NULL
	delete p;									// 如果初始化为数组,删除时候为 delete []p;
	p = NULL;


	system("pause");
    return 0;
}

输出:


编程环境:VS2015


这里展示类实例话的两种选择,一种为栈初始化,一种为堆初始化。

在用堆进行实例化的时候要注意内存问题。

猜你喜欢

转载自blog.csdn.net/feikon2/article/details/54288719