在单词搜索示例程序中,我有抽象基类Query_base,句柄类Query和派生类WordQuery。
Handle类是抽象基类和派生类的朋友,它的构造函数应该使用派生类的私有构造函数。
以下是这些类的代码:
class Query_base
{
friend class Query;
protected:
typedef TextQuery::line_no line_no;
virtual ~Query_base() { };
private:
// eval returns the |set| of lines that this Query matches
virtual std::set<line_no> eval (const TextQuery&) const = 0;
// display prints the query
virtual std::ostream& display (std::ostream& = std::cout) const = 0;
};
// handle class to manage the Query_base inheritance hierarchy
class Query
{
// these operators need access to the Query_base* constructor
friend Query operator~(const Query &);
friend Query operator|(const Query&, const Query&);
friend Query operator&(const Query&, const Query&);
public:
Query(const std::string&); // build a new WordQuery
// copy control to manage pointers and use counting
Query(const Query &c): q(c.q), use(c.use) { ++*use; }
~Query() { decr_use(); }
Query operator=(const Query&);
// interface functions: will call corresponding Query_base operations
std::set<TextQuery::line_no> eval (const TextQuery &t) const
{ return q->eval(t); }
std::ostream &display(std::ostream&os) const { return q->display(os); }
private:
Query(Query_base *query): q(query), use (new std::size_t(1)) { }
Query_base *q;
std::size_t *use;
void decr_use()
{
if (--*use == 0)
{
delete q;
delete use;
}
}
};
class WordQuery: public Query_base
{
friend class Query; // Query uses the WordQuery constructor
WordQuery(const std::string &s): query_word(s) { }
// concrete class: WordQuery defines all inherited pure virtual function
std::set<line_no> eval(const TextQuery &t) const
{ return t.run_query(query_word); }
std::ostream& display (std::ostream &os) const
{ return os << query_word; }
std::string query_word; // word for which to search
};
我试着像这样定义构造函数:
Query::Query(const std::string &s): q(WordQuery(s)) { };
但编译器不允许我这样做。
请让我知道我做错了什么。
对于那些可能面临类似问题的人,构造函数应该像这样写:
Query::Query(const std::string &s)
{ q = new WordQuery(s); use = new std::size_t(1); }