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

标签 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 处;我不是在实例化抽象类,而是从抽象类派生的类。我该如何解决它?

最佳答案

在抽象类中。

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;}

函数签名不匹配..

关于c++ - 如何实例化从抽象类派生的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22496148/

相关文章:

c++ - 使用 clang/LLVM 通过 LDFLAGS 链接 .dylib

c++ - 为什么传递给函数的指针的值没有改变?

c++ - 使用 Microsoft Visual Studio 2010 IDE 进行精确的库链接顺序控制

c++ - 7-Zip : Any good tutorials?

c++ - boost asio 套接字是否有适当的 RAII 清理

C++自动检测模板参数?

c++ - 读取文件多数据类型 (c++)

c++ - 无法使用 Crypto++ 进行 RSA 加密/解密(isValidCoding 为 false)

带分隔符的C++文件读取

c++ - 如何以及为什么要使用 Boost 信号2?