C++编程思想里的一个例子。
先看代码:
handle.hpp
#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
#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;
}
这种风格可以用在隐藏类的信息。(主要功能)
也可以减少编译时间。如果cheshire的组成改变了,之需要编译一个cpp。(按这种写法,cheshire是不易复用的)
总是,这就是典型的C++中的面向接口编程啊。
再给一段使用boost的入门代码
h文件:
#ifndef _TEST_KIN_
#define _TEST_KIN_
#include <boost/smart_ptr/shared_ptr.hpp>
#include <iostream>
void test_shared_ptr();
void test_bridge();
using namespace boost;
using namespace std;
class bridge
{
private:
class impl;
shared_ptr < impl > implSP;
public:
bridge();
void saySomething();
};
#endif // _TEST_KIN_
test_bridge.cpp
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <vector>
#include <string>
#include "test.h"
using namespace std;
//using namespace boost;
class bridge::impl{
string something;
public:
impl(){
something = "I am kinzhang.";
}
string getSomething(){return something;}
};
void bridge::saySomething(){
if(implSP){
cout << implSP->getSomething() << endl;
}
}
bridge::bridge(){
implSP = make_shared<impl>();
}
void test_bridge(){
bridge b;
b.saySomething();
}