天天看点

C++|深入理解类的封装与数据隐藏

作者:小智雅汇

封装不单纯只是提供一个封皮,封装的是数据抽象出的属性与行为,封装提供了访问控制,可以实现数据隐藏与访问接口,封装提供了作用域与命名空间的界定。封装让数据的颗粒度变得更大,有利于程序的积木式搭建。当然,封装也是继承与多态的基石。

class ClassName // member encapsulation, data hiding through access level
  // a base address, name expanding, namespace, scope
{ // {}形成封装,有数据隐藏,有接口
private: // private与{}一起形成数据隐藏,{}外面的部分(包括其子类)无法访问{}内的pvivate部分
             // (可以被内部的部分访问)
             // but not private for friends of functions or classes
    // Declarations of private
    // members appear here.
protected: // 本类、子类成员函数、友元可以访问,此外,外部不能被访问
public: // public部分形成封装的接口,与外界交互
    // Declarations of public
    // members appear here.
    // static members // 由类名即可以访问,类名相当于命名空间或标识符扩展(name expanding)
    // virtual functions // 被继承重载时可扩展
    // abstract class(virtual and "=0" notation) forms interface
    // friend ostream &operator << (ostream &, const className &);
}; // 尽量暴露方法,不要暴露数据
// static data member must be defined outside the class declaration
// Separating a class into specification and implementation files
// 在外定义成员需使用作用域限定操作符(scope resolution operator)::限定成员名称
// ReturnType ClassName :: functionName ( ParameterList ){} // member name extending           

示意图:

C++|深入理解类的封装与数据隐藏

一个简单实例:

class Rectangle
{
private:
    double width;
    double length;
    static int counting;
public:
    void setWidth(double);
    void setLength(double);
    double getWidth() const;
    double getLength() const;
    double getArea() const;
    friend ostream &operator << (ostream &, const Rectangle &);
};
int Rectangle::counting = 0;           

不同继承方式形成的访问权限:

C++|深入理解类的封装与数据隐藏

实例:

#include <stdio.h>
class A{
private:
    int x;
protected:
    int y;
public:
    int z;
    A(int a,int b,int c){
        x=a;
        y=b;
        z=c;
    }
};
class B:private A{
private:
    int p;
public:
    B(int a,int b,int c,int d):A(a,b,c){p=d;}
    int sum(){
        return  y+z;
    }
};
main()
{
    A a(1,2,3);
    printf("%d\n",a.z); // 3
    B b(1,2,3,4);
    printf("%d\n",b.sum());// 5
    //printf("%d\n",b.z);
    getchar();
}           

类封装形成的数据隐藏可以保证数据的安全性、完整性。在保证接口的稳定性后, 当外部只访问接口时,接口实现的改变以及private部分的变更,都无须变更已使用该类接口的代码。

-End-

继续阅读