C++ Access Control Modifiers / C++ 访问控制符

I saw many debates on the web about the access control modifier. And I also have some confusion although I have never used other derive method than "public". And I believe only the compiler will tell you the truth:
见到网上有很多关于C++访问控制符的问题,自己也有些迷糊。虽然自己在实际工程中从来没有用过除public以外的继承。再多的讨论都不如让编译器来告诉你事实来的实在:


// NOTICE: the lines commented out below can get compiled!
class B {
public:
void public_foo() {
cout << "public_foo" << endl;
}
protected:
void protected_foo() {
cout << "protected_foo" << endl;
}
private:
void private_foo() {
cout << "private_foo" << endl;
}
};

class D1 : public B {
public:
void test () {
B::public_foo();
B::protected_foo();
// B::private_foo();
}
};

class D2 : protected B {
public:
void test () {
B::public_foo();
B::protected_foo();
// B::private_foo();
}
};

class D3 : private B {
public:
void test () {
B::public_foo();
B::protected_foo();
// B::private_foo();
}
};

class DD1 : public D1 {
public:
void test_inherits () {
B::public_foo();
B::protected_foo();
// B::private_foo();
}
};

class DD2 : public D2 {
public:
void test_inherits () {
B::public_foo();
B::protected_foo();
// B::private_foo();
}
};

class DD3 : public D3 {
public:
void test_inherits () {
// B::public_foo();
// B::protected_foo();
// B::private_foo();
}
};

int main(int argc, const char *argv[])
{
DD1 dd1;
dd1.public_foo();
// you can't change the originally protected to public
// with public inheritance
// dd1.protected_foo();
// nor the private ones
// dd1.private_foo();

DD2 dd2;
// but you can change a public to protected
// dd2.public_foo();

DD3 dd3;
// DD3 has everthing tagged with private
// you have nothing to do with it

return 0;
}

So:
[b][list]
[*]the public/protected/private modifier for field or method declaration controls the member's access in its derived class.
[*]the public/protected/private modifier for inheriting modifies the access defined by the above rule to the modifier you used here.
[*]the modification made by the above rule only happens if the it makes the member less accessible
[/list][/b]
结论:
[list]
[b][*]public/protected/private被用在字段或方法的声明时控制的是该成员在其子类中的访问权
[*]public/protected/private被用于继承关系时可以修改上述声明的访问权为你在此指定的修饰符
[*]上述修改只在当这种修改使得成员访问权“更小”时才会发生
[/list][/b]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值