C++解析(10):struct和class的区别

0.目录

1.默认访问级别
2.默认继承方式
3.小结

1.默认访问级别

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

1250397-20181206124018378-1975601641.png

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\n", animal.get_i());
    printf("j = %d\n", 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\n", animal.get_i());
    printf("j = %d\n", 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\n", animal.get_i());
    printf("j = %d\n", 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

转载于:https://www.cnblogs.com/PyLearn/p/10076127.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值