zoukankan      html  css  js  c++  java
  • 012_linuxC++之_类的继承定义

    (一)访问控制和继承

    • 公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有保护成员来访问。
    • 保护继承(protected): 当一个类派生自保护基类时,基类的公有保护成员将成为派生类的保护成员。
    • 私有继承(private):当一个类派生自私有基类时,基类的公有保护成员将成为派生类的私有成员。

    访问权限总结出不同的访问类型,如下所示:

    访问publicprotectedprivate
    同一个类 yes yes yes
    派生类 yes yes no
    外部的类 yes no no

    (二)使用示例

     1. 在同一个类中都可以使用

     1 #include <iostream>
     2 using namespace std;
     3 class test{
     4 public:
     5         int test1;
     6 private:
     7         int test2;
     8 protected:
     9         int test3;
    10 
    11         void A(void)
    12         {
    13             test1 = 0;
    14             test2 = 0;    /*error*/
    15             test3 = 0;
    16         }
    17 };
    18 
    19 
    20 int main(int argc, char **argv)
    21 
    22 {
    23 
    24 }
    View Code

    2. 在派生类中不能访问private中的

     1 #include <iostream>
     2 using namespace std;
     3 class test{
     4 public:
     5         int test1;
     6 private:
     7         int test2;
     8 protected:
     9         int test3;
    10 
    11 };
    12 
    13 class Rectangle:public test{
    14 public:
    15         void A(void)
    16         {
    17             test1 = 0;
    18         //    test2 = 0;    /*error*/
    19             test3 = 0;
    20         }
    21 
    22 };
    23 int main(int argc, char **argv)
    24 
    25 {
    26 
    27 }
    View Code

    运行结果,注销掉就能编译成功了

    3. 外部的类使用

     1 #include <iostream>
     2 using namespace std;
     3 class test{
     4 public:
     5         int test1;
     6 private:
     7         int test2;
     8 protected:
     9         int test3;
    10 };
    11 
    12 
    13 int main(int argc, char **argv)
    14 
    15 {
    16     test S;
    17     S.test1 = 0;
    18     //S.test2 = 0;  /*error*/
    19     //S.test3 = 0;    /*error*/
    20 }
    View Code

    运行结果,外部类无法使用protected和private,注销掉就成功了

     

  • 相关阅读:
    吴太银:华为消费者云服务Cassandra使用场景与最佳实践
    使用FileZilla连接Linux
    debug 与 release
    删除cocos2dx项目模版
    [转]C/C++控制台输出时设置字体及背景颜色
    iphone调试的一些问题
    [转]Refactoring Game Entities with Components
    使用QT + cocos2dx制作工具
    [转]printf输出字体颜色
    Error: No module named books
  • 原文地址:https://www.cnblogs.com/luxiaoguogege/p/9693708.html
Copyright © 2011-2022 走看看