zoukankan      html  css  js  c++  java
  • C++解析(10):struct和class的区别

    0.目录

    1.默认访问级别

    2.默认继承方式

    3.小结

    1.默认访问级别

    • 在用struct定义类时,所有成员的默认访问级别public
    • 在用class定义类时,所有成员的默认访问级别private

    2.默认继承方式

    2.1 分别独立继承

    • struct继承struct时,默认继承方式public
    • class继承class时,默认继承方式private

    2.2 struct继承class

    struct继承class时,默认继承方式为public。

    示例代码:

    #include <stdio.h>
    
    class Biology
    {
    public:
        int i;
        int get_i() { return i; }
    };
    
    struct Animal : Biology 
    {
        int j;
        int get_j() { return j; }
    };
    
    int main()
    {
        Animal animal;
        animal.i = 1;
        animal.j = 2;
        
        printf("i = %d
    ", animal.get_i());
        printf("j = %d
    ", animal.get_j());
        
        return 0;
    }
    

    运行结果为:

    [root@bogon Desktop]# g++ test.cpp
    [root@bogon Desktop]# ./a.out 
    i = 1
    j = 2
    

    2.3 class继承struct

    class继承struct时,默认继承方式为private。

    示例代码:

    #include <stdio.h>
    
    struct Biology
    {
        int i;
        int get_i() { return i; }
    };
    
    class Animal : Biology 
    {
    public:
        int j;
        int get_j() { return j; }
    };
    
    int main()
    {
        Animal animal;
        animal.i = 1;
        animal.j = 2;
        
        printf("i = %d
    ", animal.get_i());
        printf("j = %d
    ", animal.get_j());
        
        return 0;
    }
    

    运行结果为:

    [root@bogon Desktop]# g++ test.cpp
    test.cpp: In function ‘int main()’:
    test.cpp:5: error: ‘int Biology::i’ is inaccessible
    test.cpp:19: error: within this context
    test.cpp:6: error: ‘int Biology::get_i()’ is inaccessible
    test.cpp:22: error: within this context
    test.cpp:22: error: ‘Biology’ is not an accessible base of ‘Animal’
    

    改成public继承后:

    #include <stdio.h>
    
    struct Biology
    {
        int i;
        int get_i() { return i; }
    };
    
    class Animal : public Biology 
    {
    public:
        int j;
        int get_j() { return j; }
    };
    
    int main()
    {
        Animal animal;
        animal.i = 1;
        animal.j = 2;
        
        printf("i = %d
    ", animal.get_i());
        printf("j = %d
    ", animal.get_j());
        
        return 0;
    }
    

    运行结果为:

    [root@bogon Desktop]# g++ test.cpp
    [root@bogon Desktop]# ./a.out 
    i = 1
    j = 2
    

    3.小结

    • 在用struct定义类时,所有成员的默认访问级别public
    • 在用class定义类时,所有成员的默认访问级别private
    • 默认是public继承还是private继承取决于子类而不是基类
      1. 子类是struct默认继承方式public
      2. 子类是class默认继承方式private
  • 相关阅读:
    lampp、xampp安装文档
    tomcat下配置https方式
    1.6:怎么学习Linux
    1.5:linux的应用领域
    1.3:linux的优点和缺点
    1.4:Linux发行版本详解
    1.2:liunx和unix的区别
    1.1:Linux系统简介
    mysql中获取表名&字段名的查询语句
    kettle组件-输出
  • 原文地址:https://www.cnblogs.com/PyLearn/p/10076127.html
Copyright © 2011-2022 走看看