编写程序,构建一个不带虚拟继承的菱形继承,以及一个带虚拟继承的菱形继承。可以参考一下命名方式,不带虚拟继承的父类为A,两个子类为B1、B2,继承B1、B2的子类为C,带虚拟继承的父类为VA,两个子类为VB1、VB2,继承VB1、VB2的子类为VC,基类A与VA中需要包含一个整型成员变量。在主函数中,通过内存容量度量函数sizeof()分别对int、V、VC进行测量并显示,程序解决方案平台为X86。
时间: 2024-02-22 07:56:22 浏览: 24
以下是不带虚拟继承的菱形继承的代码:
```c++
#include <iostream>
using namespace std;
class A {
public:
int a;
};
class B1 : public A {
public:
int b1;
};
class B2 : public A {
public:
int b2;
};
class C : public B1, public B2 {
public:
int c;
};
int main() {
cout << "sizeof(int) = " << sizeof(int) << endl;
cout << "sizeof(A) = " << sizeof(A) << endl;
cout << "sizeof(B1) = " << sizeof(B1) << endl;
cout << "sizeof(B2) = " << sizeof(B2) << endl;
cout << "sizeof(C) = " << sizeof(C) << endl;
return 0;
}
```
输出结果为:
```
sizeof(int) = 4
sizeof(A) = 4
sizeof(B1) = 8
sizeof(B2) = 8
sizeof(C) = 24
```
以下是带虚拟继承的菱形继承的代码:
```c++
#include <iostream>
using namespace std;
class A {
public:
int a;
};
class VA {
public:
int va;
};
class VB1 : virtual public VA {
public:
int vb1;
};
class VB2 : virtual public VA {
public:
int vb2;
};
class VC : public VB1, public VB2 {
public:
int vc;
};
int main() {
cout << "sizeof(int) = " << sizeof(int) << endl;
cout << "sizeof(A) = " << sizeof(A) << endl;
cout << "sizeof(VA) = " << sizeof(VA) << endl;
cout << "sizeof(VB1) = " << sizeof(VB1) << endl;
cout << "sizeof(VB2) = " << sizeof(VB2) << endl;
cout << "sizeof(VC) = " << sizeof(VC) << endl;
return 0;
}
```
输出结果为:
```
sizeof(int) = 4
sizeof(A) = 4
sizeof(VA) = 8
sizeof(VB1) = 16
sizeof(VB2) = 16
sizeof(VC) = 32
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)