欲写好一个类,必先将其解剖(类和对象)

来源:互联网 发布:大数据需要学什么语言 编辑:程序博客网 时间:2024/06/11 04:08

Preface

C语言最重要的特点是面向过程,而面向过程的核心是用函数实现的。
C++最重要的特点是面向对象,而面向对象的核心使用类实现的,而类中又包括了数据成员和成员函数。
像我这种C++入门级的小白,看了无数的类,听了无数的课,但真正自己写类的时候,还是叫天天不灵,叫地地不应啊~~~所以五一小长假后的第一天,鼓起勇气再听一遍网课,将类解剖一下,然后再试着重建,加油!

1.类和对象

类的组成
类名
数据成员
成员函数
访问限定符
public
private
protected
对象实例化的两种方式
从栈中实例化
从堆中实例化

从栈中实例化对象

class TV{public:    char name[20];    int type;    void changeVol();    void power();};int main(void){    TV tv;    TV tv[20];//定义对象的数组    return 0;}

从堆中实例化对象

int main(void){    TV *p = new TV();    TV *q = new TV[20];    delete p;//务必清空内存    delete []q;    return 0;}

对象成员的访问
访问单一对象
从栈中访问

int main(void){    TV tv;    tv.type = 0;    tv.changeVol();    return 0;}

从堆中访问

int main(void){    TV *p = new TV();    p->type = 0;    p->changeVol();    delete p;    p = NULL;    return 0;}

访问数组对象:使用for循环

int main(void){    TV *p = new TV[5];    for(int i=0; i<5; i++){        p[i]->type = 0;        p[i]->changeVol();    }    delete []p;    p = NULL;    return 0;}

一个小例子

#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(NULL == p){        //申请内存失败        return 0;    }    p->x = 100;    p->y = 200;    p->printX();    p->printY();    delete p;    p = NULL;    system("pause");    return 0;}
0 0