【问题标题】:Compiler error in my inheritance code in C++我的 C++ 继承代码中的编译器错误
【发布时间】:2021-10-13 16:25:44
【问题描述】:

我正在学习 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;
}

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

【问题讨论】:

  • 您认为Derived 构造函数在哪里设置x 的值?
  • 编译器错误信息是否隐藏?
  • @S.M.调用 'Base::Base()' 没有匹配的函数
  • 您对下面提出的解决方案有任何疑问或问题吗?

标签: c++ class object inheritance


【解决方案1】:

当您在Derived(int b): y(b) {} 中构造Derived 对象时,该对象的Base 部分也必须构造。由于您确实为Base 提供了一个构造函数,它采用int,因此Base 中不会有implicitly defined default constructor (即使是,int 数据成员x 也会有一个未定义的值)。因此,无法使用您对这两个类的定义在 Derived d(20) 中构造 d

您可以考虑以下方法:

// 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

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

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

这里,Derived 实例的Base 部分将具有默认值,而Derived 部分将具有明确提供的值.一般来说,这可能是一个错误逻辑性质。不过,它会编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多