温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++语言(02)——封装

发布时间:2020-07-15 02:34:07 来源:网络 阅读:249 作者:三九感冒灵 栏目:编程语言

类与封装的概念

类的封装

(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
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI