码迷,mamicode.com
首页 > 编程语言 > 详细

C++中public,protected,private的理解

时间:2018-02-25 00:08:44      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:div   prot   use   ted   友元   派生   oid   int()   pos   

 1 class BaseClass
 2 {
 3 public:
 4     int public_int;
 5 private:
 6     int private_int;
 7 protected:
 8     int protected_int;
 9 };
10 
11 class DerivedClass :public BaseClass {
12 public:
13     void UsePublicInt()
14     {
15         public_int = 1; //正确
16     }
17     void UserPrivateInt()
18     {
19         private_int = 1;//错误:成员 BaseClass::private_int不可访问
20     }
21     void UserProtectedInt()
22     {
23         protected_int = 1; //正确 
24     }
25 };
26 
27 //protected 对ProtectedDerivedClass的派生类和用户和友元函数产生影响,对ProtectedDerivedClass自身的成员函数无影响
28 class ProtectedDerivedClass :protected BaseClass {
29 public:
30     void UsePublicInt()
31     {
32         public_int = 1; //正确 BaseClass::public_int是公有的
33     }
34     void UserPrivateInt()
35     {
36         private_int = 1;//错误:成员 BaseClass::private_int不可访问
37     }
38     void UserProtectedInt()
39     {
40         protected_int = 1; //正确 
41     }
42 };
43 
44 int main()
45 {
46     BaseClass baseclass;
47     baseclass.public_int; //正确
48     baseclass.protected_int; //错误:成员 BaseClass::protected_int不可访问
49     baseclass.private_int; //错误:成员 BaseClass::private_int不可访问
50 
51     DerivedClass derivedclass;
52     derivedclass.public_int;   //正确
53     derivedclass.protected_int; //错误:成员 BaseClass::protected_int不可访问
54     derivedclass.private_int; //错误:成员 BaseClass::private_int不可访问 
55 
56     ProtectedDerivedClass protectedderivedclass;
57     protectedderivedclass.public_int = 1;//错误:成员 BaseClass::public_int不可访问 原因 ProtectedDerivedClass :protected DerivedClass,对ProtectedDerivedClass的用户而言public_int是protectd,所以无法访问
58     protectedderivedclass.protected_int; //错误:成员 BaseClass::protected_int不可访问
59     protectedderivedclass.private_int; //错误:成员 BaseClass::private_int不可访问 
60 }

 

C++中public,protected,private的理解

标签:div   prot   use   ted   友元   派生   oid   int()   pos   

原文地址:https://www.cnblogs.com/creativityroom/p/8467910.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!