C/C++知识点之C++语言(02)——封装
小标 2019-04-01 来源 : 阅读 1264 评论 0

摘要:本文主要向大家介绍了C/C++知识点之C++语言(02)——封装,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。

本文主要向大家介绍了C/C++知识点之C++语言(02)——封装,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。

C/C++知识点之C++语言(02)——封装

类的封装


(1)类通常分为以下两个部分,类的实现细节和类的使用方式
(2)使用类时不需要关心其细节,创建类时才需要考虑内部实现细节
(3)C++中使用类的成员变量来表示类的属性,用成员函数表示类的行为
C++中通过定义类成员的访问级别来实现封装机制,类的封装机制使得类的使用和内部细节相分离


#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();  //使用类变量来访问类的public成员函数

    b.age = 19;         //使用类变量来访问类的public成员,并赋值
    b.weight = 120;
    //b.height = 180;   //不可以在类的外部访问类的private成员

    b.print();

    return 0;
}


类的访问权限


(1)并不是每个类的属性都是对外公开的,因此必须在类的表示方法中定义属性和行为的公开级别,类似于文件的访问权限
(2)public:成员变量和成员函数可以在类的内部和外界访问和调用
(3)private:成员变量和成员函数只能在类的内部访问和调用


类的作用域


(1)类成员的作用域都只在类的内部,外部无法直接访问
(2)成员函数可以直接访问成员变量和调用成员函数
(3)类的外部可以通过类对象访问类的public成员
注意:类成员的作用域和访问级别没有关系
C++中struct定义的类中的所有成员默认为public


#include <stdio.h>

int i = 1;      //全局变量i

struct Test
{
private:
    int i;

public:
    int j;

    int getI()
    {
        i = 3;

        return i;
    }
};

int main()
{
    int i = 2;      //局部变量i

    Test test;      //定义类Test的变量test

    test.j = 4;     //使用类变量来访问类的public成员函

    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)在C++中提供了新的关键字class,用于定义类
(2)class和struct的用法是完全相同的
(3)class和struct定义类的区别在于默认访问权限不同(相反)
C++中要兼容C语言,而struct在C语言中已经有其意义(定义结构体),所以实际工程中我们一般只使用class关键字来定义类



/**使用struct定义类与class定义类的区别在于默认访问权限不同(相反)***/
#include <stdio.h>

struct A
{
    // defualt to public
    int i;
    // defualt to public
    int getI()
    {
        return i;
    }
};

class B
{
    // defualt to private
    int i;
    // defualt to private
    int getI()
    {
        return i;
    }
};

int main()
{
    A a;
    B b;

    a.i = 4;

    printf("a.getI() = %d\n", a.getI());

    b.i = 4;

    printf("b.getI() = %d\n", b.getI());

    return 0;
}


代码实践


使用面向对象的方法开发一个四则运算的类,见代码
(1)C++中支持类的声明和实现的分离
.h头文件中只有类的声明(成员变量和成员函数)
.cpp文件中完类的其他实现(成员函数的具体实现)


// test.cpp

#include <stdio.h>
#include "Operator.h"

int main()
{
    Operator op;
    double r = 0;

    op.setOperator('/');
    op.setParameter(9, 3);

    if( op.result(r) )
    {
        printf("r = %lf\n", r);
    }
    else
    {
        printf("Calculate error!\n");
    }

    return 0;
}

// operator
#include "Operator.h"

bool Operator::setOperator(char op)     //::表明是Operator类的成员函数
{
    bool ret = false;

    if( (op == '+') || (op == '-') || (op == '*') || (op == '/') )
    {
        ret = true;
        mOp = op;
    }
    else
    {
        mOp = '\0';     //'\0'是一个转义字符,他对应的ASCII编码值是0,本质就是0
    }

    return ret;
}

void Operator::setParameter(double p1, double p2)
{
    mP1 = p1;
    mP2 = p2;
}

bool Operator::result(double& r)
{
    bool ret = true;

    switch( mOp )
    {
        case '/':
            if( (-0.000000001 < mP2) && (mP2 < 0.000000001) )   //被除数不能为0
            {
                ret = false;
            }
            else
            {
                r = mP1 / mP2;
            }
            break;
        case '+':
            r = mP1 + mP2;
            break;
        case '*':
            r = mP1 * mP2;
            break;
        case '-':
            r = mP1 - mP2;
            break;
        default:
            ret = false;
            break;
    }

    return ret;
}

// operator.h

#ifndef _OPERATOR_H_
#define _OPERATOR_H_

class Operator
{
private:    //注意冒号不能丢
    char mOp;           //操作符
    double mP1,mP2;     //两个操作数

public:
    bool setOperator(char op);  //设置运算类型
    void setParameter(double p1, double p2);    //设置运算参数
    bool result(double& r);     //进行运算,返回值表示运算的合法性,通过引用参数返回结果
};  //分号

#endif

   

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程