码迷,mamicode.com
首页 > 编程语言 > 详细

C++--类与封装

时间:2019-05-15 18:10:04      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:turn   foo   成员函数   内存   lan   get   printf   内部实现   src   

一.类的组合
电脑一般而言是由CPU、内存、主板、键盘和硬盘等部件组合而成。下图可以表示该关系
技术图片
A.类通常分为以下两个部分
1.类的实现细节
2.类的使用方式
技术图片
1.当使用类时,不需要关心其实现细节
2.当创建类时,才需要考虑其内部实现细节

二.封装的基本概念
C++中类的封装
1.成员变量:C++中用于表示类属性的变量
2.成员函数:C++中用于表示类行为的函数
3.C++中可以给成员变量和成员函数定义访问级别--public:成员变量和成员函数可以在类的内部和外界访问和调用;private:成员变量和成员 函数只能在类的内部被访问和调用
代码示例

#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() { }
    void work() { }
};
struct Gril: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()
{
    Gril g;
    Boy b;
    return 0;
}

输出结果
技术图片
三.类成员的作用域
1.类成员的作用域都只在类的内部,外部无法直接访问
2.成员函数可以直接访问成员变量和调用成员函数
3.类的外部可以通过变量访问publi成员
4.类成员的作用域与访问级别没有关系
C++中用struct定义的类中所有成员默认为public
代码实现

#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;
}

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

在C++中提供新的关键字class用于类定义
在用struct定义类时,所有成员的默认访问级别为public
在用class定义类时,所有成员的默认访问级别为private

C++--类与封装

标签:turn   foo   成员函数   内存   lan   get   printf   内部实现   src   

原文地址:https://blog.51cto.com/13475106/2395032

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!