我的 C++ 继承代码中的编译器错误

Has*_*ude 1 c++ inheritance class object

我正在学习 C++ 中的继承。因此,每当创建类的对象时,都会调用构造函数。构造函数用于初始化类变量。

#include<bits/stdc++.h>
using namespace std;
class Base
{
    protected:
        int x;
    public:
        
        Base(int a): x(a)
        {
            cout<<"Base"<<endl;
        }
};
class Derived: public Base
{
    private:
        int y;
    public:
                                      
        Derived(int b):y(b)
        {
            cout<<"Derived"<<endl;
        }
    
        void print()
        {
            cout<<x<<" "<<y<<endl;
        }
};
int main()
{
    Derived d(20);
    d.print();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

从这里开始,我正在创建基类的对象并在其上调用打印函数。所以我应该得到输出。但是我的代码给出了编译器错误,为什么?任何人都可以帮助我理解这一点吗?

raw*_*rex 5

当您在 中构造Derived对象时Derived(int b): y(b) {}Base也必须构造此对象的一部分。既然你提供了一个构造函数Base这需要一个int不会有一个隐含定义的默认构造函数Base (即使是,该int数据成员x将有一个未定义的值)。因此,有没有办法构建dDerived d(20)两个类使用的定义。

您可以考虑以下方法:

// Inside Base class:
// We provide a default constructor
// As well as one that takes an int
Base(int a = 0): x(a) {} 

// Inside Derived class:
// We supply a value for the Base and a value for the Derived part
Derived(int b, int d): Base(b), y(d) {} 

// Inside main():
Derived d(20, 30);
d.print();
// Prints: 20 30
Run Code Online (Sandbox Code Playgroud)

当我们为 提供了默认构造函数时Base,我们甚至可以这样做,它会编译:

// Base part will be default constructed
Derived(int b): y(b) {} 
// ...Prints: 0 20
Run Code Online (Sandbox Code Playgroud)

在这里,实例的Base一部分Derived将有一个默认值,而该Derived部分将有一个明确提供给它的值。在一般情况下,这可能会是一个错误逻辑性。尽管如此,它还是会编译。