0
我有兩個類,一個是另一個的父類。他們都需要有不同的操作員功能。每個類都有一個獨特的輸出函數。這裏是他們是如何或多或少設置:C++繼承和操作符重載
template <class T>
class Tree {
protected:
T elem;
vector< Tree<T>* > children;
public:
ostream &output(ostream& stream,int level) {
stream << "Tree" << endl;
for (int j=0;j<level;j++) stream << " ";
stream << '\'' << this->elem << '\'' << endl;
for (unsigned int i=0;i<this->children.size();i++) {
this->children[i]->output(stream,level+1);
}
return stream;
}
template <class U>
friend ostream &operator<<(ostream &cout,Tree<U> &obj);
};
template <class T>
ostream &operator<<(ostream &stream,Tree<T> &obj) {
obj.output(stream,0);
return stream;
};
template <class T>
class ParseTree : public Tree<T> {
protected:
ParseTree<T>* elemTree;
vector< ParseTree<T>* > children;
public:
ostream &output(ostream& stream,int level) {
stream << "ParseTree" << endl;
if (elemTree == NULL) {
for (int j=0;j<level;j++) stream << " ";
stream << '\'' << this->elem << '\'' << endl;
}
else {
elemTree->output(stream,level+1);
}
for (unsigned int i=0;i<this->children.size();i++) {
this->children[i]->output(stream,level+1);
}
return stream;
}
template <class U>
friend ostream &operator<<(ostream &cout,ParseTree<U> &obj);
};
template <class T>
ostream &operator<<(ostream &stream,ParseTree<T> &obj) {
obj.output(stream,0);
return stream;
};
兩個輸出功能遞歸地打印出樹,但分析樹的略有不同。我遇到的問題是,當我嘗試輸出一個ParseTree時,第一次迭代來自ParseTree的輸出函數(通過流< <「ParseTree」< < endl語句確認),但所有後續請求似乎都是Tree輸出功能(如由流確認的< <「樹」< < endl語句)。每一個推到子載體上的對象都是ParseTree。我的猜測是ParseTree :: children與Tree :: children不同,並且出於某種原因上下文正在切換。有任何想法嗎?
我也不得不刪除ParseTree中的第二個孩子的定義,但這是有效的。謝謝! – 2012-03-20 20:07:23