21xrx.com
2025-03-18 02:27:44 Tuesday
文章检索 我的文章 写文章
C++如何调用子类函数
2023-07-13 12:48:06 深夜i     15     0
C++ 调用 子类函数 类继承 多态性

C++是一种广泛使用的编程语言,它支持面向对象的编程方法。在面向对象的编程中,多态是其中一个基本概念。通过多态,可以在不知道具体对象类型的情况下调用子类函数。那么在C++中如何调用子类函数呢?

假设我们有一个父类Animal,其中包含一个虚函数makeSound(),并且有两个子类Dog和Cat,它们都继承自Animal。在子类中,我们重写了makeSound()函数,以满足各自动物的特性。以下是实现的代码:

#include <iostream>
using namespace std;
class Animal {
  public:
   virtual void makeSound()
     cout << "This is the Animal's sound." << endl;
   
};
class Dog: public Animal {
  public:
   void makeSound()
     cout << "This is the Dog's sound." << endl;
   
};
class Cat: public Animal {
  public:
   void makeSound()
     cout << "This is the Cat's sound." << endl;
   
};
int main() {
  Animal *animal;
  Dog dog;
  Cat cat;
 
  animal = &dog;
  animal->makeSound();
 
  animal = &cat;
  animal->makeSound();
 
  return 0;
}

在上述代码中,我们定义了一个指向Animal对象的指针animal,并将其初始化为指向Dog和Cat对象的地址。接下来,我们调用了animal->makeSound()函数,这样可以根据实际对象的类型调用不同子类的makeSound()函数。输出结果如下:

This is the Dog's sound.
This is the Cat's sound.

通过上述例子,我们可以看出,在父类中定义虚函数,然后在子类中重写该函数,可以实现多态。在程序运行时,根据实际对象类型调用不同子类的函数。这是C++中调用子类函数的基本方法。

  
  

评论区