C++ 访问控制 public, protected, private, 友元

1. 变量属性与继承之间的关系

#include <iostream>
using namespace std;
class A {
public:
    int x;
protected:
    int y;
private:
    int z;
};

class B : public A {
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A {
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A {
    // x is private
    // y is private
    // z is not accessible from D
};

  

2. 可见性

Only members/friends of a class can see private inheritance and only members/friends of derived class can see protected inheritance

protected member provides enhanced access for derived classes

private member keep implementation details

 

3. private 成员不能直接访问, 但是可以间接的通过函数的调用进行访问. 无论是哪种形式的继承, 基类的变量都会被子类继承下来, 所不同的仅是有些变量不可访问, 即 not accessible

 

4. 友元. 一个类友元(包括友元函数或友元类的所有成员函数) 可以访问该类的任何成员( 包括成员变量和成员方法)

 

5. 除去上面所说的几条内容, 有一种技术叫做 member spy(类成员间谍), 通过该技术, 派生类可以将基类的 protected 成员修改成 public 权限, 这种技术用到了 using 关键字

 

 

posted @ 2013-12-10 19:27  SangS  阅读(1156)  评论(0编辑  收藏  举报