当前位置:编程学习 > C/C++ >>

C++类信息的隐藏

C++编程思想里的一个例子。

先看代码:

handle.hpp

[cpp] 
#ifndef HANDLE_H_ 
#define HANDLE_H_ 
 
class handle { 
    struct cheshire;  //这里通知编译器cheshire是个结构体,结构体的定义编辑器将在cpp中找到 
    cheshire* smile; 
 
public: 
    void initialize(); 
    void cleanup(); 
    int read(); 
    void change(int); 
}; 
 
#endif // HANDLE_H_ 

handle.cpp
[cpp]
#include <iostream> 
#include "handle.hpp" 
 
using namespace std; 
 
 
struct handle::cheshire { 
    int i; 
}; 
 
void handle::initialize() { 
    smile = new cheshire(); 
    smile->i = 11; 

 
void handle::cleanup() { 
    if(smile){ 
        delete smile; 
        smile = NULL; 
    } 

 
int handle::read() { 
    return smile->i; 

 
void handle::change(int x){ 
    smile->i = x; 

 
int main(){ 
    handle h; 
    h.initialize(); 
    h.change(888L); 
    std::cout<< (h.read()); 
    return 0; 

[cpp] 
 
[cpp]
 

这种风格可以用在隐藏类的信息。(主要功能)

也可以减少编译时间。如果cheshire的组成改变了,之需要编译一个cpp。(按这种写法,cheshire是不易复用的)

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,