2011-11-13 3 views
0

맨 아래의 Word 클래스 정의에서 Dict의 생성자 인 Dict (string f)을 상속 할 수 있기를 원했습니다. 그러나 직접적인 상속이 아니기 때문에 직접 할 수는 없습니다. 그것은 트리를 따르고 마지막 부모는 Element 클래스입니다.직접 부모가 아닌 기본 클래스에서 생성자를 상속하는 방법

Word 클래스 (Dict)에서 Word 클래스를 상속 받아 Word 테스트 ("test.txt")를 수행 할 수 있도록 컴파일러에게 알리는 방법은 무엇입니까? 메인에서의 인스턴스화?

#include <iostream> 
#include <vector> 
#include <sstream> 
#include <string.h> 
#include <fstream> 

using namespace std; 

class Dict { 
public: 
    string line; 
    int wordcount; 
    string word; 
    vector <string> words; 

    Dict(string f) { // I want to let Word inherit this constructor 
     ifstream in(f.c_str()); 
     if (in) { 
      while(in >> word) 
      { 
       words.push_back(word); 
      } 
     } 
     else 
      cout << "ERROR couldn't open file" << endl; 

     in.close(); 
    } 
}; 

class Element : public Dict { 
public: 
    virtual void complete(const Dict &d) = 0; 
    virtual void check(const Dict &d) = 0; 
    virtual void show() const = 0; 
}; 

class Word: public Element { 
public: 
    Word(string f) : Dict(f) { }; // Not allowed (How to fix?) 

    void complete(const Dict &d) { }; 
}; 
}; 

int main() 
{ 
    //Word test("test.txt"); 
    return 0; 
} 

답변

4

Element 클래스는 질문에 Dict 생성자를 호출 할 수있는 기능이 있어야합니다. C++ 98/03에서

,이 Element 단순히 Dict 생성자를 호출 정확히 같은 매개 변수로 생성자를 정의해야하고 Word 대신 Dict 생성자의 Element 생성자를 사용하는 것을 의미합니다.

C++ 11에서는 constructor inheritance을 사용하여 많은 타이핑을 저장하고 가능한 오류를 방지 할 수 있습니다.

2

귀하의 Element 클래스에 다음 생성자를 제공해야

Element(string iString) : Dict(iString) {;} 

그런 다음 최대 Dict에 대한 호출을 전파됩니다 Word 클래스에서 Element 생성자를 호출 할 수 있습니다.

관련 문제