在编写程序时,为了不让封装的数据类型及参数让使用者看到,只保留public部分的接口函数,将内部变量封装起来,利用结构体定义到实现函数中,可以使用如下的句柄控制:
头文件"control.h"
1 #pragma once 2 3 class Control 4 { 5 struct Cheshire; 6 //定义一个结构体,默认为权限为private,只有类的内部可以访问。 7 Cheshire* smile; 8 //定义一个结构体类型的指针,用于访问结构体的内部成员。 9 public: 10 void init();//公共成员函数 11 void clear(); 12 int read(); 13 void change(int value); 14 };
实现文件"control.cpp"
1 #include "control.h" 2 struct Control::Cheshire //结构体的实现 3 { 4 int i; 5 }; 6 void Control::init() 7 { 8 smile = new Cheshire; 9 /*开辟一块结构体类型的指针内存空间, 10 smile为Control类下面的私有成员变量, 11 但init()为内部成员函数, 12 具有访问私有成员函数权限.*/ 13 smile->i = 0; 14 //指针访问结构体的成员变量。 15 } 16 void Control::clear() 17 { 18 delete smile; 19 //释放开辟的指针内存空间 20 } 21 int Control::read() 22 { 23 return smile->i; 24 } 25 void Control::change(int value) 26 { 27 smile->i = value; 28 }
main文件"main.cpp"
1 #include "control.h" 2 3 int main(int argc,char* argv[]) 4 { 5 6 Control handle; 7 //创建一个Control对象, 8 //向自身成员函数发送消息 9 handle.init(); 10 handle.change(5); 11 handle.read(); 12 handle.clear(); 13 }
这样在头文件中就看不到类中的变量,在实现文件中隐藏了起来。