Dec 20, 2010

private继承例子

#include <iostream>
#include <map>
#include <utility>
#include <exception>
#include <iterator>
#include <string>
#include <algorithm>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& os, pair<T1,T2> p)
{
 os << p.first << ": " << p.second;
 return os;
}

class propertySet: private map<string, double>
{
public:
 inline propertySet& operator()(string k, double v)
 {
  return set(k, v);
 }
 propertySet& set(string k, double v)
 {
  this->operator[](k) = v;
  return *this;
 }
 double get(string k)
 {
  propertySet::const_iterator iter = this->find(k);
  if(iter==this->end())
   throw exception();
  return iter->second;
 }
 void print(ostream& os)
 {
  propertySet::iterator iter;
  for(iter=this->begin();iter!=this->end();++iter)
  {
   os << *iter << endl;
  }
 }
};

int main()
{
 propertySet ps;
 ps.set("scale",0.1).set("level",3);
 ps("image",5)("output",1);
 ps.print(cout);
 return 0;
}

输出
image: 5
level: 3
output: 1
scale: 0.1

0 comments: