C++深度剖析教程15 --- 类与封装

学习交流可以添加

微信读者交流①群 (添加微信:coderAllen,备注加群)
程序员技术交流①群:736386324

C++教程所有源码地址:
https://github.com/lkk789/C-Learn-Source-code


1.类的组合
电脑一般而言是由CPU,内存,主板,键盘和硬盘等部件组合而成。
在这里插入图片描述

2.类的封装
类通常分为以下两个部分
类的实现细节
类的使用方式
在这里插入图片描述
当使用类时,不需要关系其实现细节
当创建类时,才需要考虑其内部实现细节

例:
普通用户使用手机:只需要学习如何发短信,打电话,拍照等
手机开发工程师:需要考虑手机内部的实现细节

封装的基本概念
根据经验:并不是类的每个属性都是对外公开的

如:女孩子不希望外人知道自己的体重和年龄

如:男孩子不希望别知道自己的身高和收入
而一些类的属性是对外公布的

如:人的姓名,学历,国籍等
必须在类的表示法中定义属性和行为的公开级别
类似文件系统中文件的权限

C++中类的封装
成员变量:C++中用于表示类属性的变量
成员函数:C++中用于表示类行为的函数

C++中可以给成员变量和成员函数定义访问级别
public:成员变量和成员函数可以在类的内部和外界访问和调用
private:成员变量和成员函数只能在类的内部被访问和调用

15-1 类成员的访问属性

#include <stdio.h>

#include <stdio.h>

struct Biology 
{
    bool living;
};

struct Animal : Biology 
{
    bool movable;
    
    void findFood()
    { 
    }
};

struct Plant : Biology 
{
    bool growable;
};

struct Beast : Animal 
{
    void sleep() 
    { 
    }
};

struct Human : Animal 
{
    void sleep() 
    { 
        printf("I'm sleeping...\n");
    }
    
    void work() 
    { 
        printf("I'm working...\n");
    }
};

struct Girl : Human
{
private:
    int age;
    int weight;
public:
    void print()
    {
        age = 22;
        weight = 48;
        
        printf("I'm a girl, I'm %d years old.\n", age);
        printf("My weight is %d kg.\n", weight);
    }
};

struct Boy : Human
{
private:
    int height;
    int salary;
public:
    int age;
    int weight;

    void print()
    {
        height = 175;
        salary = 9000;
        
        printf("I'm a boy, my height is %d cm.\n", height);
        printf("My salary is %d RMB.\n", salary);
    }    
};

int main()
{
    Girl g;
    Boy b;
    
    g.print();
    
    b.age = 19;
    b.weight = 120;
    //b.height = 180;
    
    b.print();
    
    return 0;
}

在这里插入图片描述
3.类成员的作用域
类成员的作用域都只在类的内部,外部无法直接访问
成员函数可以直接访问成员变量和调用成员函数
类的外部可以通过类变量访问public成员
类成员的作用域与访问级别没有关系
C++中用struct定义的类中所有成员默认为public

15-2 类成员的作用域

#include <stdio.h>

int i = 1;

struct Test
{
private:
    int i;

public:
    int j;
        
    int getI()
    {
        i = 3;
        
        return i;
    }
};

int main()
{
    int i = 2;
    
    Test test;
    
    test.j = 4;
    
    printf("i = %d\n", i);              // i = 2;
    printf("::i = %d\n", ::i);          // ::i = 1;
    // printf("test.i = %d\n", test.i);    // Error
    printf("test.j = %d\n", test.j);    // test.j = 4
    printf("test.getI() = %d\n", test.getI());  // test.getI() = 3
    
    return 0;
}

在这里插入图片描述

小结
类通常可以分为使用方式和内部细节两部分
类的封装机制使得使用方式和内部细节相分离
C++中通过定义类成员的访问界别实现封装机制
public成员可以在类的内部和外界访问和调用
private成员只能在类的内部被访问和调用

发布了331 篇原创文章 · 获赞 870 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/super828/article/details/103835880
今日推荐