错误:构造函数在此上下文中受到保护

时间:2012-02-25 10:12:12

标签: c++

#include<iostream>
using namespace std;
class Base{
    private:
        int a;
    protected:
        Base(){};
        virtual ~Base(){};
};
class Derived:private Base{
    private:
        int b;
    public:
        Derived(){};
        ~Derived(){};
        void test(){
            Base world;
        };

};

int main(){
}

inherit.cc | 7 col 3 |错误:'Base :: Base()'受到保护 inherit.cc | 17 col 9 |错误:在此背景下 inherit.cc | 8 col 11 |错误:'virtual Base :: ~Base()'受到保护 inherit.cc | 17 col 9 |错误:在此上下文中

但为什么?

为什么这是正确的?

#include<iostream>
using namespace std;
class Base{
    private:
        int a;
    protected:
        Base(){};
        virtual ~Base(){};
        void test2(){};
};
class Derived:private Base{
    private:
        int b;
    public:
        Derived(){};
        ~Derived(){};
        void test(){
            test2();
        };

};

int main(){
}

3 个答案:

答案 0 :(得分:2)

在第一个示例中,您在Base类的方法test()中创建了Derived的对象。

在第二个示例中,您可以访问test2()中的protected方法BaseDerived private来自Protected

请注意类的访问说明符规则:

  

Protected访问说明符意味着声明为private的成员只能从类BUT外部访问,而只能从派生自它的类中访问。

如果是Derived继承:

  

基类的所有公共成员都成为派生类的私人成员&amp;
  基类的所有受保护成员都成为派生类的私有成员。

在例1中,
尽管Base来自Base,但它只能为Base成员函数Derived的{​​{1}}访问test()的受保护成员。{{ 1}})被调用的不是任何其他Base类对象 鉴于您无法创建Base对象。

在例2中,
在调用其成员函数(test2())的对象上调用test(),如上所述Derived类可以访问protected Base成员Base对象的Derived,其成员函数被调用,因此可以调用test2()

好读:
What are access specifiers? Should I inherit with private, protected or public?

答案 1 :(得分:0)

void Derived::test()中,您尝试创建Base类的实例。因为没有关于参数的说法 - 它试图调用Base默认构造函数,但它是protected - 而不是public

同样在Derived::test()的末尾将被称为析构函数,但它也受到保护。因此,您无法使用构造函数和析构函数

的此类修饰符创建Base类的实例

答案 2 :(得分:0)

#include<iostream>
using namespace std;
class Base{
    private:
        int a;
    protected:
        Base(){}
        Base(int a) : a(a) {}
        virtual ~Base(){}
        void test2(){}
};

class Derived:private Base{
    private:
        int b;
        Derived(int b) : Base(b) {};
    public:
        Derived() : Base() {}; // uses protected constructor
        ~Derived(){};
        Base* test(){
            new Derived(-1); // uses the other protected constructor
        };

};
相关问题