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

标签 c++ inheritance c++11

在最底层的 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/

相关文章:

c++ - 改进并行计算的内存布局

java - 为什么没有一种简单的方法可以在 Java 中复制对象?

c++ - 编译器无法对用作条件的表达式应用显式转换

C++。如何从函数写入文件

c++ - 为什么 shared_variable 在 gtest 中被重置为 nil

c++ - Windows 中的 ffmpeg/libav 链接问题

c++ - 有没有办法将 child *返回到基地*并评估哪个 child *已返回?

c++ - 确保模板参数是枚举类

c++ - 包含 Cocoa header 时出错

未检测到父类(super class)中声明的 Swift 协议(protocol)一致性