Skip to content

Commit

Permalink
Merge pull request #206 from CYP12138/master
Browse files Browse the repository at this point in the history
编译器优化sizeof,private继承访问权限更改
  • Loading branch information
Light-City committed Apr 10, 2022
2 parents f2e5dd0 + c0d76f1 commit 47397be
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 10 deletions.
21 changes: 17 additions & 4 deletions basic_content/sizeof/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ int main()
/**
* @file geninhe.cpp
* @brief 1.普通单继承,继承就是基类+派生类自身的大小(注意字节对齐)
* 注意:类的数据成员按其声明顺序加入内存,与访问权限无关,只看声明顺序。
* 注意:类的数据成员按其声明顺序加入内存,无访问权限无关,只看声明顺序。
* 2.虚单继承,派生类继承基类vptr
* @author 光城
* @version v1
Expand All @@ -117,32 +117,45 @@ class A
* int b
* short a
* long b
* 根据字节对齐4+4=8+8+8=24
* 根据字节对齐4+4+8+8=24
*
* 或编译器优化
* char a
* short a
* int b
* long b
* 根据字节对齐2+2+4+8=16
*/
class B:A
{
public:
short a;
long b;
};
/**
* 把A的成员拆开看,char为1,int为4,所以是1+(3)+4+1+(3)=12,()为字节补齐
*/
class C
{
A a;
char c;
};

class A1
{
virtual void fun(){}
};
class C1:public A1
class C1:public A
{
};


int main()
{
cout<<sizeof(A)<<endl; // 8
cout<<sizeof(B)<<endl; // 24
cout<<sizeof(B)<<endl; // 16 或 24
cout<<sizeof(C)<<endl; // 12

/**
* @brief 对于虚单函数继承,派生类也继承了基类的vptr,所以是8字节
*/
Expand Down
14 changes: 12 additions & 2 deletions basic_content/sizeof/geninhe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,24 @@ class A
* int b
* short a
* long b
* 根据字节对齐4+4=8+8+8=24
* 根据字节对齐4+4+8+8=24
*
* 或编译器优化
* char a
* short a
* int b
* long b
* 根据字节对齐2+2+4+8=16
*/
class B:A
{
public:
short a;
long b;
};
/**
* 把A的成员拆开看,char为1,int为4,所以是1+(3)+4+1+(3)=12,()为字节补齐
*/
class C
{
A a;
Expand All @@ -51,7 +61,7 @@ class C1:public A
int main()
{
cout<<sizeof(A)<<endl; // 8
cout<<sizeof(B)<<endl; // 24
cout<<sizeof(B)<<endl; // 16
cout<<sizeof(C)<<endl; // 12

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,45 @@
一、公有继承
1.基类中protected的成员
类内部:可以访问
类的使用者:不能访问
类的派生类成员:可以访问
类内部:可以访问
类的使用者:不能访问
类的派生类成员:可以访问
2.派生类不可访问基类的private成员
3.派生类可访问基类的protected成员
4.派生类可访问基类的public成员

基类 public继承 派生类

public -> public

protected -> protected

private -> 不可访问

二、私有继承
派生类不可访问基类的任何成员与函数
派生类也不可访问基类的private成员

基类 private继承 派生类

public -> private

protected -> private

private -> 不可访问

三、保护继承
派生方式为protected的继承称为保护继承,在这种继承方式下,
基类的public成员在派生类中会变成protected成员,
基类的protected和private成员在派生类中保持原来的访问权限
注意点:当采用保护继承的时候,由于public成员变为protected成员,因此类的使用者不可访问!而派生类可访问!

基类 protected继承 派生类

public -> protected

protected -> protected

private -> 不可访问


四、派生类对基类成员的访问形式
1.通过派生类对象直接访问基类成员
Expand Down

0 comments on commit 47397be

Please sign in to comment.