首页 > 解决方案 > 继承访问问题

问题描述

在执行以下与继承相关的代码时,出现以下错误“使用已删除的函数 'Derived::Derived'”。同样在注释中说,“Derived::Derived() 被隐式删除,因为默认定义会被告知错误”。有人可以帮我解决这个问题:

#include <iostream>

//BASE CLASS
class Base
{
public:
    int a;
    
    void display()
    {
        std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
    }
    
    //constructor
    Base(int la, int lb, int lc) : a {la}, b {lb}, c {lc}
    {
        
    }

protected:
    int b;

private:
    int c;
};

//DERIVED CLASS
class Derived : public Base
{
    //a from Base is Public
    //b from Base is Protected
    //c from Base has No access
    
public:
    void access_base_members()
    {
        a = 100;    //OK since a is Public in parent
        b = 200;    //OK since b is Protected type in Parent. So derived CLASS will have access
        //c = 300;    //NOK since c is private in parent and hence cannot be accessed
    }
};


int main()
{
    std::cout << "\nBase Member access=>\n\n";
    
    Base base(1,2,3);
    base.a = 10; //OK
    //base.b = 20; //NOK since Protected
    //base.c = 30; //NOK since Private
    base.display();

    Derived derived;
    derived.a = 111;        //OK since public in parent
    //derived.b = 222;        //NOK since protected members cannot have direct access in OBJECTS
    //derived.c = 333;        //NOK since private
}

标签: c++classinheritanceconstructordefault-constructor

解决方案


基类没有隐式默认构造函数,因为有显式声明的构造函数

Base(int la, int lb, int lc) : a {la}, b {lb}, c {lc}
{
    
}

所以默认必须调用基类默认构造函数的派生类默认构造函数定义为删除。

因此,编译器为此声明发出错误消息

Derived derived;

您需要显式定义派生类的构造函数。

例如,您可以将其定义为

Derived() : Base( 0, 0, 0 )
{
}

或/和

Derived(int la, int lb, int lc ) : Base( la, lb, lc )
{
}

推荐阅读