如何实例化从抽象类派生的类

时间:2014-03-19 04:22:15

标签: c++

template<class Elem>
class BinNode//Binary tree node abstract class.
{
public:
    virtual Elem& val() = 0;//return the node's element;
    virtual void setVal(const Elem& ) = 0;//set the node's element;
    virtual BinNode* left() const = 0;//return the node's left child;
    virtual BinNode* right() const = 0;//return the node's right child;
    virtual void setLeft(BinNode*) = 0;//set the node's left child's element;
    virtual void setRight(BinNode*) = 0;//set the node's right child's element;
};

template<class Elem>
class BinNodePtr:public BinNode<Elem>
{
public:
    Elem ele;//the content of the node
    BinNodePtr<Elem>* lc;//the node's left child
    BinNodePtr<Elem>* rc;//the node's right child
public:
    static int now_on;//the node's identifier
    BinNodePtr(){lc = rc = NULL;ele = 0;};//the constructor
    ~BinNodePtr(){};//the destructor
    void setVal(const Elem& e){this->ele = e;};
    Elem& val(){return ele;}//return the element of the node
    inline BinNode<Elem>* left()const//return the node's left child
    {
        return lc;
    }
    inline BinNode<Elem>* right()const//return the node's right child
    {
        return rc;
    }
    void setLeft(const Elem& e){lc->ele = e;}//to set the content of the node's leftchild
    void setRight(const Elem& e){rc->ele = e;}//to set the content of the node's rightchild
};

int main()
{
    BinNodePtr<int> root;//initiate a variable//the error is here.
    BinNodePtr<int> subroot = &root;//initiate a pointer to the variable
}

当我构建它时,编译器告诉我“无法实例化抽象类”。错误发生在BinNodePtr root;我没有实例化一个抽象类,而是一个派生自抽象类的类。我怎么能解决它?

3 个答案:

答案 0 :(得分:2)

在抽象类中。

virtual void setLeft(**BinNode***) = 0;//set the node's left child's element;
virtual void setRight(**BinNode***) = 0;//set the node's right child's element;

并在派生类

void setLeft(const **Elem**& e){lc->ele = e;}
void setRight(const **Elem**& e){rc->ele = e;}

功能签名不匹配..

答案 1 :(得分:1)

未定义以下两种方法:

virtual void setLeft(BinNode*) = 0;//set the node's left child's element;
virtual void setRight(BinNode*) = 0;//set the node's right child's element;

因为BinNodePtr中定义的方法有不同的参数:

void setLeft(const Elem& e){lc->ele = e;}
void setRight(const Elem& e){rc->ele = e;}

答案 2 :(得分:0)

因为您没有实现这些纯虚函数

virtual void setLeft(BinNode*) = 0;//set the node's left child's element;
virtual void setRight(BinNode*) = 0;//set the node's right child's element;

所以类BinNodePtr是一个抽象类。 并且有一个导入规则:您可以实例化一个抽象类,即不能使用抽象类创建类对象。

你可以阅读article