【C++深度解析】11、引入 class,类与封装的概念

1 类的关键字

  • struct 在 C 语言中已经有了自己的含义,C++ 要继续兼容
  • 在 C++ 中提供了新的关键字 class 用于类定义
  • class 和 struct 用法完全相同。

class 和 struct 有什么区别呢?

  • 在用 struct 定义类时,所有成员的默认访问级别是 public
  • 在用 class 定义类时,所有成员的默认访问级别是 private

2 类与封装的概念

  • 当使用类时,不需要关心其实现细节
  • 当创建类时,才需要考虑其内部实现细节

根据经验,类中的某些属性是对外公开的,有些是不公开的,必须在类的表示法中定义属性和行为的公开级别。

类的定义:

class 类名称
{
public:
	公有成员(外部接口)
private:
	私有成员
protected:
	保护型成员
};
  • public 成员是类与外部的接口,任何外部函数都可以访问公有类型数据和函数。
  • private 成员只允许本类中的函数访问,而类外部的任何函数都不能访问。(如果紧跟在类名称的后面声明私有成员,则关键字 private 可以省略。)
  • protected 成员与 private 类似,其差别表现在继承与派生时对派生类的影响不同。
  • public,private 和 protected 可以在类中多次出现

编程实验:

// 11-1.cpp
#include<stdio.h>
class Human
{
public:
    void sleep(){};
    void work(){};
};
class Girl : public Human
{
private:
    int age;
    int weight;
public:
    void print()
    {
        age = 22;
        weight = 45;
        printf("I'm a girl, I'm %d years old.\n", age);
        printf("My weight is %d kg.\n", weight);
    }
};
class Boy : public 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 = 130;
    // b.height = 180;		// 类外不能访问私有成员
    b.print();
    return 0;
}

3 类成员的作用域

  • 类成员的作用域都只在类的内部,外部无法直接访问
  • 成员函数可以直接访问成员变量和调用成员函数
  • 类外可以通过类变量访问 public 成员

编程实验:类成员作用域

// 11-2.cpp
#include<stdio.h>
int i = 1;
class 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);		// 私有成员不可访问
    printf("test.j = %d\n", test.j);            // test.j = 4
    printf("test.getI() = %d\n", test.getI());  // test.getI() = 3
    return 0;
}

4 四则运算示例

需求:开发一个用于四则运算的类

  • 提供 setoperator 函数设置运算类型
  • 提供setParameter 函数设置运算参数
  • 提供 result 函数进行运算
    • 其返回值表示运算的合法性
    • 通过引用参数返回结果

分析:

  • 对于使main函数来说,只需要知道怎么使用Operator即可,没有必要知道其实现
  • Operator.h头文件中只有类的声明
  • Operator.cpp中完成类的其它实现
// Operator.h
#ifndef _OPERATOR_H_
#define _OPERATOR_H_
class Operator
{
private:
    char mOp;
    double mP1;
    double mP2;
public:
    bool setOperator(char op);
    void setParameter(double p1, double p2);
    bool result(double& r);
};
#endif
// OPerator.cpp
#include"Operator.h"
bool Operator::setOperator(char op)
{
    bool ret = false;
    if ((op == '+') || (op == '-') || (op == '*') || (op == '/'))
    {
        ret = true;
        mOp = op;
    }
    else
    {
        mOp = '\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))
            {
                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;
}
// 11-3.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;
}
$ g++ 11-3.cpp Operator.cpp -o 11-3
$ ./11-3
r = 3.000000

5 小结

1、C++ 引入新的关键字 calss 用于定义类
2、struct 和 class 的区别在于默认访问级别不同
3、类的封装机制使得使用方式和内部细节相分离
4、类中有 public,private 和 protected 三种访问权限
5、C++ 中的类支持声明和实现的分离,在头文件中声明类,在源文件中实现类

发布了248 篇原创文章 · 获赞 115 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/happyjacob/article/details/104098992