C++结构体可以继承吗
时间: 2023-11-08 14:54:24 浏览: 115
在 C++ 中,结构体可以通过关键字 `struct` 进行定义,并且也可以使用继承机制来派生自其他结构体或类。因此,结构体可以进行继承。
继承机制允许一个结构体(或类)从另一个结构体(或类)继承成员变量和成员函数,从而可以重用已有的代码和定义。通过继承,子结构体可以获得父结构体的成员,并且可以添加自己的成员变量和成员函数。
下面是一个示例代码,演示了如何在 C++ 中使用结构体进行继承:
```cpp
#include <iostream>
// 定义父结构体
struct ParentStruct {
int parentVariable;
void parentMethod() {
std::cout << "Parent Method" << std::endl;
}
};
// 定义子结构体,继承自父结构体
struct ChildStruct : public ParentStruct {
int childVariable;
void childMethod() {
std::cout << "Child Method" << std::endl;
}
};
int main() {
ChildStruct child;
// 访问父结构体的成员变量和成员函数
child.parentVariable = 10;
std::cout << "Parent Variable: " << child.parentVariable << std::endl; child.parentMethod();
// 访问子结构体自己的成员变量和成员函数
child.childVariable = 20;
std::cout << "Child Variable: " << child.childVariable << std::endl;
child.childMethod();
return 0;
}
```
在上述示例中,定义了一个名为 `ParentStruct` 的父结构体,其中包含一个整型成员变量 `parentVariable` 和一个成员函数 `parentMethod`。然后,定义了一个名为 `ChildStruct` 的子结构体,通过关键字 `: public ParentStruct` 实现了对父结构体的继承。子结构体中增加了一个整型成员变量 `childVariable` 和一个成员函数 `childMethod`。
在 `main` 函数中,创建了一个 `ChildStruct` 结构体对象 `child`。可以通过该对象访问父结构体的成员变量和成员函数,也可以访问子结构体自己的成员变量和成员函数。最后输出结果如下:
```
Parent Variable: 10
Parent Method
Child Variable: 20
Child Method
```
可以看到,通过继承,子结构体成功地从父结构体继承了成员变量和成员函数,并且还可以添加自己的成员。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)