21xrx.com
2024-09-19 09:30:22 Thursday
登录
文章检索 我的文章 写文章
C++中实现多态的方法
2023-06-26 08:10:10 深夜i     --     --
C++ 多态 虚函数 继承 重载

多态(Polymorphism)是面向对象程序设计中的一个重要概念,是指同一种操作或方法,在不同的对象上具有不同的行为表现。C++作为一门具有面向对象特性的编程语言,可以用多种方法实现多态,以下是其中的三种常见方法:

1. 虚函数

虚函数是C++中实现多态的基础,通过在基类中声明虚函数,在派生类中重写该函数,就可以实现不同对象调用同一函数但表现不同的效果。例如:


class Shape {

public:

  virtual void draw() {}

};

class Circle : public Shape {

public:

  void draw() override

    cout << "This is a circle." << endl;

  

};

class Square : public Shape {

public:

  void draw() override

    cout << "This is a square." << endl;

  

};

int main() {

  Shape* shape1 = new Circle();

  Shape* shape2 = new Square();

  shape1->draw();

  shape2->draw();

  return 0;

}

运行结果为:


This is a circle.

This is a square.

2. 纯虚函数

纯虚函数是在虚函数的基础上进一步抽象,将虚函数声明为纯虚函数,即在函数声明后加上 " = 0 ",表示该函数没有实际的实现,需要在派生类中重新实现。例如:


class Animal {

public:

  virtual void move() = 0;

};

class Dog : public Animal {

public:

  void move() override

    cout << "The dog is running." << endl;

  

};

class Cat : public Animal {

public:

  void move() override

    cout << "The cat is jumping." << endl;

  

};

int main() {

  Animal* animal1 = new Dog();

  Animal* animal2 = new Cat();

  animal1->move();

  animal2->move();

  return 0;

}

运行结果为:


The dog is running.

The cat is jumping.

3. 虚析构函数

当一个类中定义了虚函数,它的析构函数也应该定义为虚函数。在销毁一个对象的时候,如果该对象指向的是一个派生类对象,而该基类中的析构函数不是虚函数,那么只会调用该基类的析构函数,而不会调用派生类的析构函数,可能会导致内存泄漏问题。因此,为了避免这种情况,必须将基类的析构函数定义为虚函数。例如:


class Person {

public:

  Person() cout << "Person created." << endl;

  virtual ~Person() cout << "Person destroyed." << endl;

};

class Student : public Person {

public:

  Student() cout << "Student created." << endl;

  ~Student() cout << "Student destroyed." << endl;

};

int main() {

  Person* p = new Student();

  delete p;

  return 0;

}

运行结果为:


Person created.

Student created.

Student destroyed.

Person destroyed.

总之,在C++中实现多态的方法有很多,在实际的编程过程中,需要根据实际情况选择合适的方法,保证程序的高效运行。

  
  

评论区

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