【问题标题】:Is there another way to explicitly initialise parent class?是否有另一种方法来显式初始化父类?
【发布时间】:2021-03-17 09:15:41
【问题描述】:

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

例如:

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

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

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

【问题讨论】:

  • 您可以在??? 所在的位置创建它。 Parent(std::fstream(filename))
  • Where can I create this stream variable???? 创建它有什么问题?
  • 但是当涉及到更复杂的工作时,我不能只用一个函数/行来做到这一点。
  • But when it comes to more complicated work, I couldn't do this in just one function/line. 为什么你认为会这样?您需要展示一个示例,说明您认为在哪种情况下它不起作用。
  • 或者直接调用lambda。

标签: c++ oop inheritance


【解决方案1】:

cmets 已经展示了一种可能的方法,所以你可以这样做:

#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 的直接基类,所以我相应地修改了代码。否则它不会编译。

【讨论】:

  • 这不太可能奏效,因为std::fstream 不可复制。
  • 嗯,它在我的机器上与 GCC 9 配合得很好。我什至可以从Parent的构造函数中的文件流中读取一些内容,如下所示:Parent(std::fstream f) { std::string s; std::getline(f, s); std::cout &lt;&lt; s &lt;&lt; std::endl; } 看起来不需要复制。
猜你喜欢
  • 2019-01-02
  • 2014-05-24
  • 2022-01-03
  • 1970-01-01
  • 2016-06-02
  • 2013-12-28
  • 2014-04-18
  • 1970-01-01
  • 2020-03-08
相关资源
最近更新 更多