2014-03-19 3 views
0
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 루트에 있습니다. 나는 추상 클래스를 인스턴스화하지 않고 추상 클래스에서 파생 된 클래스입니다. 어떻게 해결할 수 있습니까?추상 클래스에서 파생 된 클래스를 인스턴스화하는 방법

+1

당신은 정의'setLeft'와'BinNodePtr''에 다른 매개 변수를 setRight'. – Brian

답변

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; 

그래서 클래스를 구현하지 않기 때문에

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

기능 서명이 일치하지 않는 파생 클래스에서

..

+0

이 오류를 감지하는 데 도움이되도록하려면 파생 클래스의 함수 헤더 다음에 재정의 (override) 될 것으로 예상되는 경우 'override'라는 단어를 쓸 수 있습니다. 그런 다음 서명이 일치하지 않으면 컴파일러는 해당 행에 오류를 정확하게 표시합니다. –

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

BinNodePtr은 추상 클래스입니다. 그리고 가져 오기 규칙이 있습니다. 추상 클래스를 인스턴스화 할 수 있습니다. 즉, 추상 클래스를 사용하여 클래스 객체를 만들 수 없다는 것입니다.

article을 읽을 수 있습니다

관련 문제