省流:父类中私有成员也是被子类继承下去了,只是由编译器给隐藏后访问不到

  • 父类中所有非静态成员属性都会被子类继承下去

验证

环境:为搜死丢丢2022 & win11

打开x64 Native Tools Command Prompt for VS 2022

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.3.0
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

D:\Microsoft Visual Studio\2022\Community>F: //切换至F盘

F:\>cd source/repos/Project1 //打开项目所在文件夹

F:\source\repos\Project1>dir //查看文件夹下文件
驱动器 F 中的卷是 Oher
卷的序列号是 987F-AA63

F:\source\repos\Project1 的目录

2022/08/18 15:27 <DIR> .
2022/08/17 09:38 <DIR> ..
2022/08/17 08:50 1,436 Project1.sln
2022/08/17 08:54 6,620 Project1.vcxproj
2022/08/17 08:54 965 Project1.vcxproj.filters
2022/08/17 08:50 168 Project1.vcxproj.user
2022/08/17 08:54 <DIR> x64
2022/08/18 15:27 261 源.cpp
2022/08/18 15:24 275,968 源.exe
2022/08/18 15:24 227,282 源.obj
7 个文件 512,700 字节
3 个目录 321,091,620,864 可用字节

F:\source\repos\Project1>cl /d1 reportSingleClassLayoutson 源.cpp //指令
用于 x64 的 Microsoft (R) C/C++ 优化编译器 19.33.31629 版
版权所有(C) Microsoft Corporation。保留所有权利。

源.cpp

class son size(16):
+---
0 | +--- (base class Base)
0 | | m_A
4 | | m_B
8 | | m_C
| +---
12 | m_D
+---
D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\include\ostream(378): warning C4530: 使用了 C++ 异常处理程序,但未启用展开语义。请指定 /EHsc
D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\include\ostream(371): note: 在编译 类 模板 成员函数 “std::basic_ostream<char,std::char_traits<char>> &std::basic_ostream<char,std::char_traits<char>>::operator <<(unsigned __int64)”时
源.cpp(21): note: 查看对正在编译的函数 模板 实例化“std::basic_ostream<char,std::char_traits<char>> &std::basic_ostream<char,std::char_traits<char>>::operator <<(unsigned __int64)”的引用
源.cpp(21): note: 查看对正在编译的 类 模板 实例化“std::basic_ostream<char,std::char_traits<char>>”的引用
Microsoft (R) Incremental Linker Version 14.33.31629.0
Copyright (C) Microsoft Corporation. All rights reserved.

/out:源.exe
源.obj

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;


class Base {
public:
int m_A;
protected:
int m_B;
private:
int m_C;//私有成员只是被隐藏了,但还是会继承下去
};
//公共继承
class son :public Base {
public:
int m_D;
};


int main() {
cout << "size of son= " << sizeof(son) << endl;
return 0;
}