Posted on 2009-06-28 00:18
Ben仔 閱讀(664)
評論(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指針施放哦