C++类和对象

对象是具体的事物,类是从对象中抽象出来的。

类的定义:数据成员(成员变量)、成员函数(方法)

类的访问限定符: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







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值