Use and example of multi-layer inheritance (inheritance) in C + +

Source: Internet
Author: User
Tags abstract eval inheritance new set

Dynamic binding can only be applied to virtual functions (virtual function), through pointers (->) or references (.). Call Declares a base class pointer, binding a derived class object;

You can use "Shared_ptr<abstract_base_class> P" (new Derived_class (para)); The form of dynamically binding derived classes;

You can add an interface (interface) to a dynamic base class, so that the Ufida function accesses the private member variable of the base class; And the concrete operation is written into the interface;

If a derived class does not implement the pure virtual function of the abstract base class, it inherits the function, and the derived class is also an abstract base class;

Abstract base classes cannot create specific objects, but you can implement specific methods that provide inheritance for derived classes;

Object-Oriented Programming: Abstraction (abstraction), i.e. data abstraction (abstraction), Inheritance (inheritance), polymorphism (polynorphism), dynamic binding (dynamical binding).

The specific code is as follows, as detailed in the note:

* * * cppprimer.cpp * * Created on:2013.11.7 * author:caroline//*eclipse CDT, gcc 4.8.1*/ #include <iostream> #include <fstream> #include <sstream> #include <string> #include &l t;vector> #include <memory> #include <algorithm> #include <iterator> #include <set&  
Gt  
      
#include <map> using namespace std;  
Class QueryResult;  
      
std::ostream& print (std::ostream& os, const queryresult &AMP;QR);  
    Class Textquery {public:using line_no = std::vector<std::string>::size_type;  
    Textquery (std::ifstream&);  
QueryResult query (const std::string&) const; private:std::shared_ptr<std::vector<std::string> > file; File content std::map<std::string, std::shared_ptr<std::set<line_no> > > WM;  
      
The collection of words and line numbers}; /* Place each line in text, in file (vector), to form the mapping of Word and line number (set)/Textquery::textquery (std::ifstReam &is): File (new std::vector<std::string>) {std::string text;  
        while (Std::getline (is, text)) {file->push_back (text);  
        int n = file->size ()-1;  
        Std::istringstream line (text);  
        Std::string word;  
            while (line >> word) {auto& lines = Wm[word];  
            if (!lines) Lines.reset (new set<line_no>);  
        Lines->insert (n);  
}} class QueryResult {friend std::ostream& print (std::ostream&, const queryresult&);  
    Public:using line_no = std::vector<std::string>::size_type; QueryResult (std::string s,//query word std::shared_ptr<std::set<line_no>> p,//Match line number St D::shared_ptr<std::vector<std::string>> f)://Input file sought (s), lines (p), file (f) {} St  
    D::set<line_no>::iterator begin () {return lines->begin ();} StD::set<line_no>::iterator End () {return lines->end ();}  
Std::shared_ptr<std::vector<std::string>> Get_file () {return file;} Private:std::string sought; Find string std::shared_ptr<std::set<line_no>> lines; Line number set std::shared_ptr<std::vector<std::string>> file;  
      
File collection};
/* Find the collection of specified sought, return iterators, incoming string and set*//* More highlights: http://www.bianceng.cnhttp://www.bianceng.cn/programming/cplus/*/ QueryResult textquery::query (const std::string& sought) const {static Std::shared_ptr<std::set<line_no&gt  
    ;> NoData (new std::set<line_no>);  
    Auto loc = Wm.find (sought); if (loc = = Wm.end ()) return QueryResult (sought, nodata, file); Not found, do not print else return QueryResult (sought, loc->second, file);  
      
Print by line number}; std::string make_plural (std::size_t ctr, const std::string& Word, const std::string ending) {retur N (Ctr > 1)? Word + Ending : Word; } std::ostream& Print (std::ostream& os, const queryresult &AMP;QR) {os << qr.sought << "occurs" << qr.lines->size () << "" << make_plural (Qr.lines->size (), "Time", "s") &L  
    t;< Std::endl; for (auto num: *qr.lines) os << "\ t (line" << num+1 << ")" << * (Qr.file->begin () +num  
    ) << Std::endl;  
return OS;  
    } void Runqueries (Std::ifstream &infile) {textquery TQ (infile);  
        while (true) {std::cout << ' enter word to look for, or Q to quit: ";  
        std::string s; if (!) ( Cin>>s) | |  
        s = = "q") break;  
    Print (Std::cout, tq.query (s)) << Std::endl;  
}/* Abstract base class, no public member */class Query_base {friend Class Query;  
    protected:using line_no = textquery::line_no; Virtual ~query_base () = default; Virtual destructor private:virtual queryresult eval (const TEXTQuery&) const = 0;  
Pure virtual function Virtual Std::string rep () const = 0;  
      
}; Provide interface (interface) class Query {friend query operator~ (const query &) for query_base;//Fetch anti-friend query ope rator| (const query&, const query&); Fetch or friend Query operator& (const query&, const query&);  
    Take the Public:query (const std::string&); QueryResult eval (const textquery &t) Const {return q->eval (t);}//Valuation associated Query std::string rep () const {return Q->rep (); //Generate a string version of query Private:query (std::shared_ptr<query_base> query): Q (query) {} std::shared_ptr<q Uery_base> Q;  
      
Use dynamic binding}; Overloaded output (<<) operator Std::ostream & operator<< (std::ostream &os, const Query &query) {return o  
S << query.rep ();  
    }//Word query class Wordquery:public query_base {friend class query; Wordquery (const std::string &s): Query_word (s) {} QueryResult EvAl (const textquery &t) Const {return t.query (Query_word);}  
    Std::string Rep () const {return query_word;};  
Std::string Query_word;  
      
};  The query interface implements dynamic binding Wordquery inline Query::query (const std::string &s): Q (New Wordquery (s)) {}//Reverse query class Notquery:public query_base {friend query operator~ (const query &);//friend is the inverse function notquery (const query &A  
    MP;Q): Query (q) {} std::string Rep () const {return "~ (" +query.rep () + ")";}  
    QueryResult eval (const textquery &t) const;  
query query;  
      
};  
To achieve reverse operation, dynamic binding Notquery object//End use of Wordquery class, query construction needs wordquery, and then into the notquery; Inline query operator~ (const query &operand) {return std::shared_ptr<query_base> (new Notquery (operand))  
; ///Two Yuan query, no eval, then inherit pure virtual function class Binaryquery:public Query_base {protected:binaryquery (const query & Amp;l, const Query &r, std::string s): LHS (L), RHS (R), Opsym (s) {} std::String Rep () const {return "(" + lhs.rep () + "" + Opsym + "" + rhs.rep () + ")";}  
    Query LHS, RHS;  
Std::string Opsym;  
      
};  
    Fetch and Query class Andquery:public binaryquery {friend query operator& (const query&, const query&);  Andquery (const query& left, const query& right): Binaryquery (left, right, "&") {} QueryResult eval  
(const textquery&) const;  
      
}; Inline Query operator& (const query& LHS, const query& RHS) {return std::shared_ptr<query_base> (n  
EW Andquery (LHS, RHS)); }//Fetch or query class Orquery:public binaryquery {friend Query operator|  
    (const query&, const query&); Orquery (const query& left, const query& right): Binaryquery (left, right, "|")  
{} queryresult eval (const textquery&) const;  
      
}; Inline Query operator| (const query& LHS, const query& RHS) {return std::shared_ptr<query_base> (NEW orquery (LHS, RHS)); } queryresult orquery::eval (const textquery& text) Const {Auto right = Rhs.eval (text), left = Lhs.eval  
    (text);  
    Auto Ret_lines = std::make_shared<std::set<line_no> > (Left.begin (), Left.end ());  
    Ret_lines->insert (Right.begin (), Right.end ());  
Return QueryResult (Rep (), Ret_lines, Left.get_file ()); } queryresult andquery::eval (const textquery& text) Const {Auto left = Lhs.eval (text), right = Rhs.eva L (text);  
    The call is Wordquery's eval auto ret_lines = std::make_shared<std::set<line_no>> (); Std::set_intersection (Left.begin (), Left.end (), Right.begin (), Right.end (), Std::inserter (*ret_lines, Ret_li  
    Nes->begin ()));  
Return QueryResult (Rep (), Ret_lines, Left.get_file ()); } queryresult notquery::eval (const textquery& text) Const {Auto result = Query.eval (text);//Call Wordque  
    Ry.eval; Auto Ret_lines = Std::make_shared<std::set<line_nO>> ();  
    Auto Beg = Result.begin (), end = Result.end ();  
    Auto Sz = Result.get_file ()->size ();  
        For (size_t n=0 N!=sz; ++n) {if (Beg==end | | *beg!= N) ret_lines->insert (n);  
    else if (beg!=end) ++beg;  
Return QueryResult (Rep (), Ret_lines, Result.get_file ()); BOOL Get_word (std::string& str) {std::cout << "Enter word to look for, or Q to quit:" <&lt ;  
    Std::endl; if (!) ( Std::cin >> str) | |  
        str = = "Q") {std::cout << str;  
    return false;  
        } else{std::cout << str;  
    return true;  
    int main (void) {Std::ifstream infile;  
    Infile.open ("StoryDataFile.txt");  
    Textquery file = infile;  
    Query q = ~query ("Alice"); Query q = query ("Hair") |  
    Query ("Alice");  
    Query q = query ("Hair") & Query ("Alice"); Query q = query ("fiery") & Query ("Bird ") |  
    Query ("Wind");  
    Const AUTO RESULTS = q.eval (file);  
    cout << "\nexecuting Query for:" << Q << Endl;  
    Print (cout, results) << Endl;  
    Infile.close ();  
      
return 0; }

Output:

Executing Query for: ((Fiery & bird) | wind)  
((Fiery & bird) | wind) occurs 3  
    (line 2) her Daddy say s when the Wind Blows   
    (line 4) Like a fiery bird in flight  
    (line 5) A beautiful fiery bird he tells her

Author: csdn Blog spike_king

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.