公共,受保护,私人

时间:2010-08-02 14:04:36

标签: c++ access-modifiers

看看这段代码:

#include <iostream>

using namespace std;

class A
{
private:
    int privatefield;
protected:
    int protectedfield;
public:
    int publicfield;
};

class B: private A
{
private:
    A a;
public:
    void test()
    {
        cout << this->publicfield << this->protectedfield << endl;
    }
    void test2()
    {
        cout << a.publicfield << a.protectedfield << endl;
    }
};

int main()
{
    B b;
    b.test();
    b.test2();
    return 0;
}

B可以访问this-&gt; protectedfield但不能访问a.protectedfield。为什么?然而,B是A的子类。

3 个答案:

答案 0 :(得分:3)

<强>这 - &GT; protectedfield: A的B enherits,这意味着protectedfield现在是它自己的属性,所以它能够访问它。

<强> a.protectedfield: a是B类的成员,该成员具有受保护的protectedfield变量。 B无法触摸它,因为受保护意味着只能从A内部访问。

答案 1 :(得分:3)

B只能访问受保护的字段本身或其他类型的B对象(或者可能从B派生,如果它们将它们视为B-s)。

B无法访问同一继承树中任何其他无关对象的受保护字段。

Apple无权访问Orange的内部,即使它们都是Fruit。

class Fruit
{
    protected: int sweetness;
};

class Apple: public Fruit
{
    public: Apple() { this->sweetness = 100; }
};

class Orange: public Fruit
{
public:
    void evil_function(Fruit& f)
    {
        f.sweetness = -100;  //doesn't compile!!
    }
};

int main()
{
    Apple apple;
    Orange orange;
    orange.evil_function(apple);
}

答案 2 :(得分:0)

让我们用小部分打破整个代码。复制并粘贴这两个代码并尝试编译!!!!

#include <iostream>
using namespace std;
class A
{
private:
    int privatefield;
protected:
    int protectedfield;
public:
    int publicfield;
};

int main()
{
    A a;
    cout<<a.publicfield;
    cout<<a.privatefield;/////not possible ! private data can not be seen by an object of that class
    cout<<a.protectedfield;////again not possible. protected data is like privete data except it can be inherited by another.If inherited as private then they are private,if as protected then protected and if as public then also protected.
}

现在B将A类继承为私有

#include <iostream>

using namespace std;

class A
{
private:
    int privatefield;
protected:
    int protectedfield;
public:
    int publicfield;
};

class B: private A
{
private:
    A a;
public:
    void test()
    {
        cout << this->publicfield << this->protectedfield << endl;
    }
    void test2()
    {
        cout << a.publicfield << endl;
    }
};
int main()
{
    /*Now B will have both public and protected data as private!!!!
    That means
     B now looks like this class


     Class B
     {  

        private:
        int protectedfield;
        int publicfield;
     }

     As we have discussed private/protected data can not be accessed by object of the class
     so you you can not do things like this

     B b;
     b.protectedfield; or b.publicfield;

     */
    B b;
    b.privatefield;////Error !!!
    b.protectedfield/////error!!!!
}

谢谢!