21xrx.com
2024-09-17 04:18:36 Tuesday
登录
文章检索 我的文章 写文章
C++中的多态性示例
2023-07-04 23:30:47 深夜i     --     --
C++ 多态性 示例

在C++中,多态性是一种关键概念,它可以提高代码的灵活性和可重用性。多态性是指同一个操作符或方法可以被不同的对象调用,从而实现不同的行为。在本文中,我们将讨论C++中多态性的示例。

1. 虚函数

虚函数是实现多态性的主要机制之一。它允许子类实现自己的版本,并重写其父类的函数。在下面的示例中,我们将使用虚函数来实现多态性:


class Animal {

public:

  virtual void makeSound()

    std::cout << "The animal makes a sound." << std::endl;

  

};

class Cat : public Animal {

public:

  void makeSound()

    std::cout << "Meow." << std::endl;

  

};

class Dog : public Animal {

public:

  void makeSound()

    std::cout << "Woof." << std::endl;

  

};

int main() {

  Animal* animal1 = new Cat();

  Animal* animal2 = new Dog();

  animal1->makeSound();

  animal2->makeSound();

  delete animal1;

  delete animal2;

  return 0;

}

在上面的示例中,我们定义了一个名为Animal的基类,它有一个虚函数makeSound()。我们还定义了两个子类Cat和Dog,它们都重写了makeSound()函数。我们在主函数中创建了一个指向Cat对象和一个指向Dog对象的Animal指针。当我们调用它们的makeSound()函数时,它们分别会输出"Meow."和"Woof."。

2. 纯虚函数

纯虚函数是另一种有助于实现多态性的机制。相比于虚函数,它们必须在子类中被重写,否则子类无法被实例化。在下面的示例中,我们将使用纯虚函数来实现多态性:


class Shape {

public:

  virtual double getArea() = 0;

};

class Rectangle : public Shape {

public:

  Rectangle(int w, int h) : width(w), height(h) {}

  double getArea() {

    return width * height;

  }

private:

  int width;

  int height;

};

class Circle : public Shape {

public:

  Circle(int r) : radius(r) {}

  double getArea() {

    return 3.14 * radius * radius;

  }

private:

  int radius;

};

int main() {

  Shape* shape1 = new Rectangle(5, 6);

  Shape* shape2 = new Circle(3);

  std::cout << "Area of rectangle: " << shape1->getArea() << std::endl;

  std::cout << "Area of circle: " << shape2->getArea() << std::endl;

  delete shape1;

  delete shape2;

  return 0;

}

在上面的示例中,我们定义了一个名为Shape的抽象基类,它有一个纯虚函数getArea()。我们还定义了两个子类Rectangle和Circle,它们都实现了getArea()函数。在主函数中,我们创建了一个指向Rectangle对象和一个指向Circle对象的Shape指针。当我们调用它们的getArea()函数时,它们分别会计算并输出矩形和圆形的面积。

总结

在C++中,多态性是一个非常重要的概念。它可以让程序员编写出更灵活和可重用的代码。在本文中,我们介绍了两种实现多态性的机制:虚函数和纯虚函数。虚函数允许子类重写基类函数,而纯虚函数则确保子类必须重写该函数才能实例化。有了这些工具,我们可以更好地组织我们的代码,让其更具可读性和可维护性。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复