Posted on 2009-06-28 00:18
Ben仔 阅读(655)
评论(0) 编辑 收藏 引用 所属分类:
c++
一般设计私有成员或者一些不想公开的到头文件的接口,可以尝试这个方法:
头文件:
1 //PimplSample.h
2 struct impl;
3
4 class CPimplSample
5 {
6 public:
7 CPimplSample();
8 ~CPimplSamle();
9 void DoSomething();
10 private:
11 impl* m_pImpl;
12
13 }
cpp:
1 //PimplSample.cpp
2 include "PimplSample.h"
3 include <string>
4 include <iostream>
5
6 struct impl{
7 void DoAnthorThing(){
8 std:cout << s << "\n";
9 }
10 std::string s;
11 }
12
13 CPimplSample::CPimplSample():m_pImpl(new imple(){
14 m_pImpl->s = "Hello Impl";
15 }
16
17 CPimplSample::~CPimplSample(){
18 delete m_pImpl;
19 }
20
21 CPimplSample::DoSomething(){
22 m_pImpl->DoAnthorThing();
23 }
这样把要隐藏的属性和接口都写在cpp文件上就可以不外露到头文件上了,记得析构函数把impl指针施放哦