子类怎么调用爷类的虚函数
时间: 2024-05-17 19:14:10 浏览: 15
子类可以通过调用爷类的虚函数来实现对爷类的虚函数进行重写。具体的调用方式为:
1. 在子类中定义与爷类相同的虚函数,在子类中重写该函数。
2. 在子类中使用爷类指针或引用指向子类对象,然后通过该指针或引用调用虚函数。
下面是一个示例代码:
```cpp
#include <iostream>
class Grandfather {
public:
virtual void virtualFunction() {
std::cout << "Grandfather's virtual function" << std::endl;
}
};
class Father : public Grandfather {
public:
void virtualFunction() override {
std::cout << "Father's virtual function" << std::endl;
}
};
class Son : public Father {
public:
void virtualFunction() override {
std::cout << "Son's virtual function" << std::endl;
}
};
int main() {
Son son;
// 使用爷类指针调用虚函数
Grandfather* ptr = &son;
ptr->virtualFunction(); // 输出:Son's virtual function
// 使用爷类引用调用虚函数
Grandfather& ref = son;
ref.virtualFunction(); // 输出:Son's virtual function
return 0;
}
```
在上面的示例中,子类Son中重写了爷类Grandfather的虚函数virtualFunction()。通过爷类指针ptr或引用ref指向子类对象son,并调用虚函数virtualFunction()时,会根据实际对象的类型来确定要调用的虚函数版本,从而实现了对爷类的虚函数的调用。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)