【问题标题】:Why object of derived class d cannot call the protected member function of the class base?为什么派生类d的对象不能调用类基的受保护成员函数?
【发布时间】:2020-02-28 10:06:52
【问题描述】:

这里派生类d的对象不能调用类基的受保护成员函数。

#include <iostream>

using namespace std;

class base
{
protected:
    int i,j;
    void setij(int a,int b)
    {
        i=a;
        j=b;
    }
    void showij()
    {
        cout<<i<<" "<<j<<endl;
    }
};

class derived : protected base
{
    int k;
public:
    void show()
    {
        base b;
        b.setij(10,20);
        b.showij();
    }

};

int main()
{
    base b;
    derived d;
    d.setij(3,4);
    d.showij();
    d.show();
    return 0;
}

我希望输出是10 20,但编译器显示错误。

【问题讨论】:

  • 错误是什么?
  • 你不能在derived之外调用函数,在main内。

标签: c++ inheritance access-control protected


【解决方案1】:

您使用了protected 继承。问题不在于派生无法访问基类的受保护方法,而在于您无法从derived 之外访问基类方法。

如果你不知道受保护的继承意味着什么,你可以阅读这里Difference between private, public, and protected inheritance

我怀疑你想在这里使用protected 继承(你为什么要这样做?)。把它改成public继承,你的代码应该没问题:

class derived : public base ...

PS:错误消息应该告诉您实际问题是什么(尽管以一种神秘的方式)。请下次将其包含在问题中。如果你不能理解它,可能其他人会。

【讨论】:

    【解决方案2】:

    这段代码有一个很多错误。即使将类derived的继承从protected改为public,仍然存在以下问题:

    1. 在类derived 中,语句b.setij(10,20);b.showij(); 仍会产生编译器错误。请参阅Why can't a derived class call protected member function in this code? 以获得很好的解释。简短的解释:一个方法只能调用它最初被调用的对象的基类中的受保护方法。

    2. 函数main 将无法调用d.setij(3,4);d.showij();,因为这些是base 类中的受保护方法。

    这应该运行:

    #include <iostream>
    
    using namespace std;
    
    class base
    {
    protected:
        int i,j;
        void setij(int a,int b)
        {
            i=a;
            j=b;
        }
        void showij()
        {
            cout<<i<<" "<<j<<endl;
        }
    };
    
    class derived : public base
    {
        int k;
    public:
        void show()
        {
            this->setij(10,20);
            this->showij();
        }
    
    };
    
    int main()
    {
        derived d;
        d.show();
        return 0;
    }
    

    【讨论】:

    • 我知道我写错了 cod 但感谢您帮助我忘记删除此问题但感谢您更满意
    猜你喜欢
    • 2013-03-05
    • 2023-03-07
    • 2014-09-12
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多