在最底层的 Word 类定义中,我希望能够继承 Dict 的构造函数,即 Dict(string f) 构造函数。但是,我不能直接这样做,因为它不是直接继承;它遵循一棵树,它的最后一个父类是 Element 类。
我怎样才能让编译器知道让Word类继承自基类的instructor(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;
}
最佳答案
Element
类必须公开调用相关Dict
构造函数的能力。
在 C++98/03 中,这意味着 Element
必须定义一个具有完全相同参数的构造函数,它只调用 Dict
构造函数,然后 Word
将使用 Element
构造函数而不是 Dict
构造函数。
在 C++11 中,您可以使用 constructor inheritance以节省大量输入并防止可能的错误。
关于c++ - 如何从非直接父基类继承构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109557/