对象是具体的事物,类是从对象中抽象出来的。
类的定义:数据成员(成员变量)、成员函数(方法)
类的访问限定符:1、public(公共的)2、protected(受保护的)3、private(私有的)
从栈中实例化
Coordinate coor;
coor.x=10;
coor.y=20;
栈中实例化之后内存自动清除。
从堆中实例化
Coordinate *p=new Coordinate();
p->x=100;
p->y=200;
堆中实例化不一定成功,所以需要判断一下:
if(p==NULL)
{ return 0;}
堆中实例化之后需要清除内存,即:
delete p;
p=NULL;
#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()
{
Coordinate coor;
coor.x=10;
coor.y=20;
coor.printX();
coor.printY();
Coordinate *p=new Coordinate();
if(p==NULL)
{
return 0;
}
p->x=100;
p->y=200;
p->printX();
p->printY();
delete p;
p=NULL;
return 0;
}
10
20
100
200