1.Loki的下载地址 http://sourceforge.net/projects/loki-lib/
2.把loki库考到自己的工程下
3.引入
#include "loki/Singleton.h" using namespace Loki;
4.定义单键
typedef SingletonHolder<fish, CreateUsingNew, PhoenixSingleton> TheFish;
详细的代码如下:
animal.h
#ifndef ANIMAL_H_H #define ANIMAL_H_H class animal { public: animal(); ~animal(); void eat(); void sleep(); virtual void breathe(); }; #endif
animal.cpp
#include "animal.h" #include <iostream> using namespace std; animal::animal() { } animal::~animal() { } void animal::eat() { } void animal::sleep() { } void animal::breathe() { cout<<"animal breathe"<<endl; }
fish.h
#include "animal.h" #ifndef FISH_H_H #define FISH_H_H class fish:public animal { public: void breathe(); }; #endif
fish.cpp
#include "fish.h" #include <iostream> using namespace std; void fish::breathe() { cout<<"fish bubble"<<endl; }
EX10.CPP
#include "animal.h" #include "fish.h" #include <iostream> #include "loki/Singleton.h" using namespace Loki; using namespace std; typedef SingletonHolder<fish, CreateUsingNew, PhoenixSingleton> TheFish; void fn(animal *pAn) { pAn->breathe(); } void main() { //animal *pAn; //fish fh; //pAn=&fh; //fn(pAn); TheFish::Instance().breathe(); int n; cin>>n; }