What is polymorphism in C++

Polymorphism:

Different types of objects respond differently to the same message

If there are cat class, dog class, pig class at this time. There are show functions in the three types. What should I do to display the three types normally?

First write three categories:

Then define the objects separately, and then call the show function:

    cat a; dog b; pig c;
    a.show();
    b.show();
    c.show();

This is the way of ordinary definition, how to put the three things together and write it out?


Inherit all three things from the animal class, and then use the type conversion method between the base class and the derived class to convert the derived class into a base class object.

As shown below:

Define an array of base classes, and then use knowledge such as virtual functions and type conversion to store objects of different derived classes.

When processing the set of objects one by one, each object will automatically know which version of the show function should be executed according to its own type and internal knowledge of the class.

So that different objects have different responses to the same message.

#include<iostream>
using namespace std;

class animal
{
public:
	virtual void show()
	{
		cout << "我是animal类" << endl;
	}
};

class dog :public animal
{
public:
	void show()
	{
		cout << "我是dog类" << endl;
	}
};

class cat :public animal
{
public:
	void show()
	{
		cout << "我是cat类" << endl;
	}
};

class pig :public animal
{
public:
	void show()
	{
		cout << "我是pig类" << endl;
	}
};

int main()
{
	cat a; dog b; pig c;
	animal *x[3] = { &a, &b, &c };
	
	for (int i = 0; i < 3; i++)
	{
		x[i]->show();
	}
	system("pause");
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/112384884