资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

类与封装的概念

类的封装

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

公司主营业务:成都网站建设、做网站、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。成都创新互联是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。成都创新互联推出宁德免费做网站回馈大家。

#include 

#include 

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 

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 

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 
#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++语言(02)——封装
当前网址:http://cdkjz.cn/article/ppjcss.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220