c++类的访问权限

类成员访问权限

class Base
{
private:
    int a;
public:
    int b;
    void foo()
    {
        cout << a << b << d << endl; //OK: 类体内可以访问任何private、public、protected成员
    }
protected:
    int d;
};

class Derived1: public Base
{
public:
	void get()
	{
		cout << b << d << endl;  //OK: 继承类可以访问基类的public、protected成员
		cout << a << endl;       //错误:继承类不能访问private成员
	}    
};

int main()
{
    Base b;
    cout << b.a << endl;        //错误:实例化对象不能访问private成员
    cout << b.d << endl;        //错误:实例化对象不能访问protected成员
    cout << b.b << endl;        //OK:实例化对象能访问public成员
}

继承时的访问权限

派生类只能访问基类的public和protected成员,而这两个成员在派生类中的新的访问权限由继承关系确定:

继承关系 public变为… protected变为…
public public protected
protected protected protected
private private private
class Base
{
private:
    int a;
public:
    int b;
protected:
    int d;
};

class Derived1: public Base
{
};

class Derived2: protected Base
{
};

class Derived3: private Base
{
};

int main()
{
    Derived1 d1;
    cout << d1.b << endl; //OK: b在Derived1还是public
    cout << d1.d << endl; //错误: d在Derived1是protected
    
    Derived2 d2;
    cout << d2.b << endl; //错误: b在Derived2是protected
    cout << d2.d << endl; //错误: d在Derived2是protected
    
    Derived3 d3;
    cout << d3.b << endl; //错误: b在Derived3是private
    cout << d3.d << endl; //错误: d在Derived3是private
}

猜你喜欢

转载自blog.csdn.net/weixin_43762200/article/details/85262804
今日推荐