(8)类和对象

#include <iostream>
using namespace std;

//类												|	class TV
//目的不同抽象出的信息不同						|	{
//选择性的暴露 访问限定符public protected private	|		public:
//												|		char name[20];
//												|		int type;
//												|		void changeVol();
//												|		void power();
//												|	};
												
//对象的定义										|
/*												|
从栈实例化对象:									|	从堆中实例化对象
这种方式使用完之后系统会自动的把占用的内存释放掉	|	int main(void)
int main(void)                                  |   {
{												|		TV *p = new TV();
	TV tv; //定义一个对象						|		TV *q = new TV[20];
	TV tv[20]; //定义一个对象的数组				|		delete p;
	return 0;									|		delete []q;                                            
}												|		return 0;
												|	}
*/

//对象成员的访问
/*
从栈实例化的对象									|	从堆上实例化的对象                               
int main(void)									|	int main(void)								int main(void)
{												|	{											{
	TV tv;										|		TV *p = new TV(); //指针的类型是TV			TV *p = new TV[5];
	tv.type = 0;								|		p->type = 0;								for(int i=0; i<5; i++)
	tv.changeVol();								|		p->changVol();								{
	return 0;									|		delete p;  //最后别忘了删除它					p[i]->type = 0;
}												|		p = NULL;										p[i]->changeVol();
												|		return 0;									}
												|	}												delete []p;
																									p = NULL;
																									return 0;
																								}
*/																									

class coord
{
public:
	int x;
	int y;
	void printx()
	{
		cout << x << endl;
	}
	void printy()
	{
		cout << y << endl;
	}
};
int main()
{
	coord coo;
	coo.x = 10;
	coo.y = 20;
	coo.printx();
	coo.printy();

	coord *p = new coord();
	if (NULL == p) //如果分配内存失败
	{
		return -1;
	}
	p->x = 30;
	p->y = 40;
	p->printx();
	p->printy();
	delete p;
	p = NULL;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/nuc_sheryl/article/details/81101917