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\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
posted @ 2018-12-06 13:00  PyLearn  阅读(369)  评论(0编辑  收藏  举报