首页 > 解决方案 > 还有另一种方法来显式初始化父类吗?

问题描述

在子类中完成一些更改后,我正在寻找一种方法来启动我的父类。

前任:

class Parent {
public:
    Parent(stream f) {
    //some code
    }
};

class Child : public Parent {
public:
    Child(string fileName) : Parent(???) {    // Line 10
    //some code
    }
};

在第 10 行,我应该给出使用“fileName”创建的 fstream。我在哪里可以创建这个流变量?

标签: c++oopinheritance

解决方案


评论已经显示了一种可能的方式,所以你可以这样做:

#include <fstream>
#include <string>

class Parent {
public:
    Parent(std::fstream f) {
        // some code
    }
};

class Child : public Parent {
public:
    // Do it like this:
    Child(std::string fileName) : Parent(std::fstream(fileName)) {
        // some code
    }
};

还有一件事:Parent显然需要是 的直接基类Child,所以我相应地修改了代码。否则它不会编译。


推荐阅读