【问题标题】:Inheritance Access Issue继承访问问题
【发布时间】:2021-07-24 00:19:14
【问题描述】:

在执行以下与继承相关的代码时,出现以下错误“使用已删除的函数 '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++ class inheritance constructor default-constructor


    【解决方案1】:

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

    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 )
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2011-04-05
      • 1970-01-01
      相关资源
      最近更新 更多