c/c++ 继承与多态 文本查询的小例子(智能指针版本)

为了更好的理解继承和多态,做一个文本查询的小例子。

接口类:Query有2个方法。

  • eval:查询,返回查询结果类QueryResult
  • rep:得到要查询的文本

客户端程序的使用方法:

//查询包含Daddy的文本所在的行
Query q("Daddy");
//查询不包含Alice的文本所在的行
Query q = ~Query("Alice");
//查询,有fiery或者bird的行
Query q = Query("fiery") | Query("bird");
//查询,既有fiery又bird的行,或者有wind的行
Query q = Query("fiery") & Query("bird") | Query("wind");

接口类:Query,有一个私有的父类Query_base的智能指针。

  • 父类Query_base有子类WordQuery,NotQuery,BinaryQuery(AndQuery,OrQuery)。

  • 子类负责把单个的查询结果,进行加工。比如做And处理,或者Or处理。

Query.h

#ifndef __QUERY_H__
#define __QUERY_H__

#include <string>
#include <memory>
#include <iostream>
#include "TextQuery.h"

class QueryResult;
class Query;

class Query_base{
  friend class Query;
 protected:
  using line_no = TextQuery::line_no;
  virtual ~Query_base() = default;
 private:
  virtual QueryResult eval(const TextQuery&) const = 0;
  virtual std::string rep() const = 0;
};

class Query{
  friend Query operator~(const Query&);//需要访问私有的构造函数
  friend Query operator|(const Query&, const Query&);//需要访问私有的构造函数
  friend Query operator&(const Query&, const Query&);//需要访问私有的构造函数
 public:
  Query(const std::string&);//构建一个新的WordQuery
  // 接口函数:调用对应的Query_base操作
  QueryResult eval(const TextQuery& t) const{
    return q->eval(t);
  }
  std::string rep()const{
    return q->rep();
  }

 private:
  Query(std::shared_ptr<Query_base> query)
    :q(query){
    std::cout << "Query pri:" << std::endl;
  }
  std::shared_ptr<Query_base> q;
  
};

class WordQuery : public Query_base{
  friend class Query;//Query 使用WordQuery的私有构造函数
  WordQuery(const std::string& s)
    : query_word(s){
    std::cout << "WordQuery:" << s << std::endl;
  }
  QueryResult eval(const TextQuery& t)const{
    return t.query(query_word);
  }
  std::string rep()const{
    return query_word;
  }

  std::string query_word;
};

class NotQuery : public Query_base{
  friend Query operator~(const Query&);
  NotQuery(const Query& q)
    :query(q){
    std::cout << "NotQuery" << std::endl;
  }
  std::string rep() const {
    return "~(" + query.rep() + ")";
  }
  QueryResult eval(const TextQuery&)const;
  Query query;
};

inline Query operator~(const Query& op){
  //return std::shared_ptr<Query_base>(new NotQuery(op));
  std::shared_ptr<Query_base> tmp(new NotQuery(op));
  return Query(tmp);
}


class BinaryQuery : public Query_base{
 protected:
  BinaryQuery(const Query& l, const Query& r,
	      std::string s)
    : lhs(l), rhs(r), opSym(s){
    std::cout << "BinaryQuery" << std::endl;
  }
  std::string rep() const {
    return "(" + lhs.rep() + " "
      + opSym + " "
      + rhs.rep() + ")";
  }
  Query lhs, rhs;
  std::string opSym;
};

class AndQuery : public BinaryQuery{
  friend Query operator&(const Query&, const Query&);
  AndQuery(const Query& l, const Query& r)
    : BinaryQuery(l, r, "&"){
    std::cout << "AndQuery" << std::endl;
  }
  QueryResult eval(const TextQuery&) const;
};

inline Query operator&(const Query& lhs, const Query& rhs){
  return std::shared_ptr<Query_base>(new AndQuery(lhs, rhs));
}

class OrQuery : public BinaryQuery{
  friend Query operator|(const Query&, const Query&);
  OrQuery(const Query& l, const Query& r)
    : BinaryQuery(l, r, "|"){
    std::cout << "OrQuery" << std::endl;
  }
  QueryResult eval(const TextQuery&) const;
};

inline Query operator|(const Query& lhs, const Query& rhs){
  return std::shared_ptr<Query_base>(new OrQuery(lhs, rhs));
}

#endif

Query.cpp

#include "Query.h"
#include <algorithm>

/*
std::ostream& operator<<(std::ostream& os, const Query& q){
  //Query::rep通过它的Query_base指针对rep()进行虚调用
  return os << q.rep();
}
*/
Query::Query(const std::string& s) : q(new WordQuery(s)){
    std::cout << "Query pub" << std::endl;
}

QueryResult NotQuery::eval(const TextQuery& text)const{
  //通过Query运算对象对eval进行虚调用
  auto result = query.eval(text);
  //开始时结果set为空
  auto ret_lines = std::make_shared<std::set<line_no>>();
  auto beg = result.begin();
  auto end = result.end();
  //对于输入文件的每一行,如果该行不在result当中,则将其添加到ret_lines
  auto sz = result.get_file()->size();
  for(size_t n = 0; n != sz; ++n){
    //如果还没有处理完result的所以行
    //检查当前行是否存在
    if(beg == end || *beg != n){
      ret_lines->insert(n);
    }
    else if(beg != end){
      ++beg;//继续获取reslut的下一行
    }
  }

  return QueryResult(rep(), ret_lines, result.get_file());
}

QueryResult AndQuery::eval(const TextQuery& text)const{
  //通过Query成员lhs,rhs进行虚调用
  //调用eval返回每个对象的QueryResult
  auto right = rhs.eval(text);
  auto left  = lhs.eval(text);
  //保存left和right交集的set
  auto ret_lines =
    std::make_shared<std::set<line_no>>();
  //将两个范围的交集写入一个目的迭代其中。
  std::set_intersection(left.begin(), left.end(),
			right.begin(), right.end(),
			inserter(*ret_lines, ret_lines->begin()));
  return QueryResult(rep(), ret_lines, left.get_file());
}

QueryResult OrQuery::eval(const TextQuery& text)const{
  //通过Query成员lhs,rhs进行虚调用
  //调用eval返回每个对象的QueryResult
  auto right = rhs.eval(text);
  auto left  = lhs.eval(text);
  //将左侧运算对象的行号拷贝到结果set中
  auto ret_lines =
    std::make_shared<std::set<line_no>>(left.begin(), left.end());
  //插入右侧运算对象所得的行号
  ret_lines->insert(right.begin(), right.end());
  //返回一个新的QueryResult,它表示lhs和rhs的并集
  return QueryResult(rep(), ret_lines, right.get_file());
}

QueryResult.h

#ifndef __QUERYRESULT_H__
#define __QUERYRESULT_H__

#include <iostream>
#include <set>
#include <vector>
#include <string>
#include <memory>

class QueryResult{
  friend std::ostream& print(std::ostream&, const QueryResult&);
public:
  using line_no = std::vector<std::string>::size_type;
  using Iter = std::set<line_no>::iterator;
  QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p,
              std::shared_ptr<std::vector<std::string>> f):
    sought(s), lines(p), file(f){}
    Iter begin() const {return lines->begin();}
    Iter end() const {return lines->end();}
    std::shared_ptr<std::vector<std::string>> get_file() const{
      return file;
    }
private:
  std::string sought;//查询的单词                                                    
  std::shared_ptr<std::set<line_no>> lines;//出现的行号                                   
  std::shared_ptr<std::vector<std::string>> file;
};
//QueryResult类的友元声明
std::ostream& print(std::ostream&, const QueryResult&);

#endif

TextQuery.h

#ifndef __TEXTQUERY_H__
#define __TEXTQUERY_H__

#include "QueryResult.h"
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <set>
#include <vector>
#include <string>
#include <memory>

using namespace std;
class TextQuery{
 public:
  using line_no = std::vector<std::string>::size_type;

  TextQuery(ifstream& is);  
  QueryResult query(const std::string &sought) const;
 private:
  std::shared_ptr<std::vector<std::string>> file;
  std::map<std::string, std::shared_ptr<std::set<line_no>>> wm;
};

#endif

TextQuery.cpp

#include "TextQuery.h"

using namespace std;

TextQuery::TextQuery(ifstream& is) : file(new vector<string>){
  string text;
  while(getline(is, text)){//读文件的每一行                                   
    file->push_back(text);
    int n = file->size() - 1;//当前行号                                       
    istringstream line(text);//将行文本分解为单词                             
    string word;
    while(line >> word){
      //非常重要,必须用引用,要不然就会拷贝一个新的set给lines,不是原来的    
      auto &lines = wm[word];//lines是shared_ptr                              
      if(!lines)
	lines.reset(new set<line_no>);
      lines->insert(n);
    }
  }
}

QueryResult TextQuery::query(const string &sought) const{
  //如果没有找到sought,返回指向此set的一个智能指针                           
  static shared_ptr<set<line_no>> nodata(new set<line_no>);
  auto ret = wm.find(sought);
  if(ret == wm.end()){
    return QueryResult(sought, nodata, file);//没有找到                       
  }
  else{
    return QueryResult(sought, ret->second, file);
  }
}


main.cpp

#include "Query.h"

//QueryResult的友元函数                                                         
ostream& print(ostream& os, const QueryResult& qr){
  os << qr.sought << " 出现了:" << qr.lines->size() << "次" << endl;
  for(auto num : *qr.lines){
    os << "\t(行号 " << num + 1 << ")"
       << *(qr.file->cbegin() + num) << endl;
  }
  return os;
}

int main(){
  ifstream infile("/home/ys/cpp/thread/oop/TextQuery/search_text");
  TextQuery tq(infile);
  //Query q = Query("fiery") & Query("bird") | Query("wind");//OK
  //Query q = Query("fiery") | Query("bird");//OK
  //Query q("Daddy");//OK
  Query q = ~Query("Alice");//OK
  print(std::cout, q.eval(tq)) << std::endl;
}

编译方法:

g++ -g Query.cpp TextQuery.cpp main.cpp -std=c++11

用于查询的文本文件

Alice Emma has long flowing red hair.
Her Daddy says when the wind blows
through her hair, it looks almost alive,
like a fiery bird in flight.
A beautiful fiery bird, he tells her,
magical but untamed.
" Daddy , shush, there is no such thing,"
she tells him, at the same time wanting
him to tell her more.
Shyly, she asks, "I mean, Daddy , is there?"

Query q = Query("fiery") & Query("bird") | Query("wind");的执行结果:

((fiery & bird) | wind) 出现了:2次
	(行号 2)Her Daddy says when the wind blows
	(行号 4)like a fiery bird in flight.

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

posted @ 2019-01-10 22:44  小石王  阅读(681)  评论(0编辑  收藏  举报