您的位置:首页 > 编程语言 > C语言/C++

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

2013-12-10 19:27 218 查看
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 关键字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: