如何从非直接父类基类继承构造函数

时间:2011-11-13 04:14:02

标签: c++ inheritance c++11

在最底层的Word类定义中,我希望能够继承Dict的构造函数Dict(string f)。但是,我不能直接这样做,因为它不是直接继承;它跟随一棵树,它的最后一个父元素是Element类。

如何让编译器知道让Word类从基类的讲师(Dict)继承,以便我可以执行Word测试(“test.txt”);在main中实例化?

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

2 个答案:

答案 0 :(得分:4)

Element类必须公开调用相关Dict构造函数的能力。

在C ++ 98/03中,这意味着Element必须定义一个构造函数,该构造函数具有完全相同的参数,只需调用Dict构造函数,然后Word将使用Element {1}}构造函数而不是Dict构造函数。

在C ++ 11中,您可以使用constructor inheritance来节省大量输入并防止可能的错误。

答案 1 :(得分:2)

您的Element类应该提供以下构造函数:

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

然后,您就可以从Element类调用Word构造函数,该构造函数会将调用传播到Dict

相关问题