简体   繁体   English

当派生类无法轻松地将参数传递给基类时,如何调用基类构造函数?

[英]How to call the base class constructor when the derived class can not easily pass the parameters to the base class?

Let say I have a base and a derived class. 假设我有一个基类和一个派生类。 In the standard derived class constructor I can call the Base class constructor with the required parameter (CASE1 below). 在标准派生类构造函数中,我可以使用所需参数(下面的CASE1)调用基类构造函数。 However, if the derived class constructor accepts a json string, I need to first extract the field containing the value for the param_base and then call the base class constructor with this parameter. 但是,如果派生类构造函数接受json字符串,则需要首先提取包含param_base值的param_base ,然后使用此参数调用基类构造函数。 How do I do that in C++? 如何在C ++中做到这一点?

class Base {
    int param_base;
public:
    Base(int x) : param_base(x) {}
};

class Derived : public Base{
    int param_derived;
public:
    Derived(int d, int b): Base(b), param_derived(d) {}; // CASE1
    Derived(std::string json_str) {  // CASE2
        int base_param = prase(json_str, "b_field");
        // How do I construct the base class with the parsed "base_param" ?
    }
};

You can write a function or lambda to do the work, then call it. 您可以编写一个函数或lambda来完成工作,然后调用它。

int do_stuff(const std::string& json_str) {
  return 42; // really parse json and extract int value
}

then 然后

Derived(std::string json_str) : Base(do_stuff(json_str) {}

lambda version: lambda版本:

Derived(std::string json_str) : Base([&json_str](){ return 42;}()) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM