c++ mooc 类和对象

  • 结构化程序设计

    c语言: 程序 = 数据结构 + 算法

    程序右全局变量和互相调用的函数组成,算法以函数实现,对数据结构进行操作

    不足:函数与其操作的数据结构没有直观联系;函数规模增加程序难以理解;没有封装和隐藏的概念,当数据结构改变时,数      据结构的使用需要一一修改

  • 面向对象程序设计

    c++:类+类+····

    设计方法:

  1. 某类客观事物共同属性归纳为一个数据结构
  2. 将这些类所能进行的行为也归纳出来,为函数,用来操作数据结构(即抽象过程)
  3. 将数据结构与操作数据结构的函数捆绑在一起形成类 (即封装过程)

    四个基本特点:抽象、封装、继承、多态

    类 = 成员变量+成员函数

    对象:类定义的变量,也叫实例

class Rectangle:   //Rectangle为类
{
    public:
        int width,height;
        int init(w,h){width=w; height=h;}
        int area(){return width*height;}
        int prem(){return 2*(width+height);}
};


int main(){
Rectangle r;  //r为对象也叫Rectangle类的实例
int w=1,h=2;
r.init(w,h);
cout<<r.area();
return 0;
}

    对象空间只包含类的成员变量大小,不包含成员函数,成员函数被所有对象共享

    对象之间可以用“=”赋值,不可以比较

    类的定义和成员函数可以分开写

class Rectangle:   //Rectangle为类
{
    public:
        int width,height;
        int init(w,h);
        int area();
        int prem();
};

int Rectangle::init(w,h){width=w; height=h;}
int Rectangle::area(){return width*height;}
int Rectangle::prem(){return 2*(width+height);}

    使用成员函数仍旧需要用对象来调用

  • 使用类的成员变量和成员函数
//方式1
Rectangle r1;
r1.w=5;

//方式2
Rectangle r1,r2;
Rectangle *p1 = &r1;
Rectangle *p2 = &r2;
p1->w=5;
p2->init(7,1);

//方式3
Rectangle r;
Rectangle &rr = r;
rr.init(7,1);
  •     类成员的可访问范围
class className{
    private:
        //私有属性和函数
    protected:
        //保护属性和函数
    public:
        //共有属性和函数
};

  如果缺省关键字,则默认私有

  类的成员函数内部可以访问:当前对象的全部属性函数,同类的其他对象的全部属性和函数

  成员函数以外的地方:仅可访问类的对象的公有部分

  设置私有成员(隐藏),是为了强制对成员变量的访问必须通过成员函数,修改成员变量属性时只需修改成员函数即可。

  成员函数也可以函数重载和缺省,注意避免二义性

猜你喜欢

转载自blog.csdn.net/scarletteshu/article/details/103396308