C++中如何在没有子类构造函数的情况下将值传递到基类的构造函数中?

Ala*_*ain 3 c++ inheritance

在 C++ 中,我创建了一个名为parent 的基类。在此类中,我创建了一个可以采用一个参数的构造函数。我的子类名称是child。我的子类中没有任何构造函数。我的代码如下:

#include<iostream>
using namespace std;
class parent{
public:
    parent(int number){
        cout<<"Value of the number from parent class is: "<<number<<endl;
    }
};
class child: public parent{
public:
    child(): parent(10){
    }
};
int main()
{
    child ob(100);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行上面的代码时,编译器“没有显示调用‘child::child(int)’的匹配函数”。

我不想在子类中创建任何参数化构造函数。如何传递父类构造函数的值?我怎么解决这个问题?

Som*_*ude 5

您有三种选择:

  1. 不使用参数,仅使用child默认构造

  2. 创建一个child采用所需参数的构造函数(可能具有默认值)

  3. 将构造函数拉入类parentchild

    class child : public parent {
    public:
        using parent::parent;  // Add the parent constructor to this scope
    
        child() : parent(10) {
        }
    };
    
    Run Code Online (Sandbox Code Playgroud)