如何实例化从抽象类派生的类
How to instantiate a class derived from a abstract class
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;}
以下两个方法没有定义:
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;}
因为你没有实现这些纯虚函数
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
是一个抽象类。还有一个导入规则:你可以实例化一个抽象类,也就是说你不能用抽象类创建一个类对象。
你可以阅读这篇文章
相关文章:
- 如何在从抽象基派生的类中实现相同的方法?
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 从从该抽象类派生的 Python 对象强制转换C++抽象类C++
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- 如何防止派生类成为 c++ 中的抽象类?
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 复制从抽象类派生的对象
- OOP - 抽象类类型,初始化基类和派生类中的变量
- 确保派生的类实现至少是来自抽象类(C )的两种方法之一
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++
- 派生类使用的抽象类的方法
- 使用从WINRT网格类派生的抽象类时,Casttobase未解决的外部符号错误
- 基类的派生类,用作抽象类
- 多个"level"派生抽象类
- 尝试定义派生自抽象类的类类型的对象时出错
- 纯抽象类和派生类型的实例化
- 如何在派生实例化之前创建抽象类
- 从抽象类派生的类的对象应在免费商店中
- 派生抽象类中的纯虚方法
- 在c++中创建派生抽象类的实例