3

看看这段代码:

#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->protectedfield,但不能访问 a.protectedfield。为什么?然而 B 是 A 的子类。

4

3 回答 3

3

this->protectedfield: B继承了A,这意味着protectedfield现在是它自己的一个属性,所以它可以访问它。

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

于 2010-08-02T14:09:33.393 回答
3

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

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

苹果无权访问橙子的内部,即使它们都是水果。

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);
}
于 2010-08-02T14:14:43.180 回答
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!!!!
}

谢谢!

于 2013-06-11T11:57:51.377 回答