c ++继承和运算符重载

时间:2012-03-20 19:55:30

标签: c++ inheritance operator-overloading

我有两个班,一个是另一个班的父母。它们都需要具有不同的运算符<<功能。每个类都有一个独特的输出函数。以下是它们或多或少的设置方式:

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略有不同。我遇到的问题是,当我尝试cout&lt;&lt; ParseTree第一次迭代来自ParseTree的输出函数(由流&lt;&lt;“ParseTree”&lt;&lt; endl语句确认),但所有后续请求似乎都是Tree的输出函数(由流&lt;&lt;确认) ;“树”&lt;&lt; endl语句)。推送到子矢量上的每个对象绝对是ParseTree。我的猜测是ParseTree :: children与Tree :: children不同,并且由于某种原因,上下文正在切换。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

使用类型为virtual的参数,仅输出operator<<并定义Tree<T>一次。这应该足够了。