C++ 中的多态性 (polymorphism) - Polymorphism in C++

C++ 中的多态性 (polymorphism) - Polymorphism in C++

                                                   ->Function Overloading (函数重载)
            ->编译时多态 (Compile time Polymorphism)->
                                                   ->Operator Overloading (运算符重载)

Polymorphism-> 

            ->运行时多态 (Runtime Polymorphism)->Function Overriding (函数覆盖)
  • 封装性
    封装是指将一个计算机系统中的数据以及与这个数据相关的一切操作语言 (即描述每一个对象的属性以及其行为的程序代码) 组装到一起,一并封装在一个有机的实体中,把它们封装在一个模块中,也就是一个类中,为软件结构的相关部件所具有的模块性提供良好的基础。在面向对象技术的相关原理以及程序语言中,封装的最基本单位是对象,而使得软件结构的相关部件的实现“高内聚、低耦合”的“最佳状态”便是面向对象技术的封装性所需要实现的最基本的目标。对于用户来说,对象是如何对各种行为进行操作、运行、实现等细节是不需要刨根问底了解清楚的,用户只需要通过封装外的通道对计算机进行相关方面的操作即可。大大地简化了操作的步骤,使用户使用起计算机来更加高效、更加得心应手。

  • 继承性
    继承性是面向对象技术中的另外一个重要特点,其主要指的是两种或者两种以上的类之间的联系与区别。继承是后者延续前者的某些方面的特点,而在面向对象技术则是指一个对象针对于另一个对象的某些独有的特点、能力进行复制或者延续。如果按照继承源进行划分,则可以分为单继承 (一个对象仅仅从另外一个对象中继承其相应的特点) 与多继承 (一个对象可以同时从另外两个或者两个以上的对象中继承所需要的特点与能力,并且不会发生冲突等现象)。如果从继承中包含的内容进行划分,则继承可以分为四类,分别为取代继承 (一个对象在继承另一个对象的能力与特点之后将父对象进行取代)、包含继承(一个对象在将另一个对象的能力与特点进行完全的继承之后,又继承了其他对象所包含的相应内容,结果导致这个对象所具有的能力与特点大于等于父对象,实现了对于父对象的包含)、受限继承、特化继承。

  • 多态性
    从宏观的角度来讲,多态性是指在面向对象技术中,当不同的多个对象同时接收到同一个完全相同的消息之后,所表现出来的动作是各不相同的,具有多种形态。从微观的角度来讲,多态性是指在一组对象的一个类中,面向对象技术可以使用相同的调用方式来对相同的函数名进行调用,即便这若干个具有相同函数名的函数所表示的函数是不同的。

1. 多态性 (polymorphism)

多态性指的是获得多种形态的能力。在 OOP (object-oriented programming,面向对象程序设计) 中,多态性指的是用同样的函数名称表示多个函数,而这些函数是不同对象的成员。C++ 多态意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
多态性一词意味着具有多种形式。简而言之,我们可以将多态定义为消息以多种形式显示的能力。

Real life example of polymorphism, a person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.
现实生活中的多态示例,一个人同时可以具有不同的特征。就像男人在同一时间是父亲、丈夫、雇员。因此,同一个人在不同情况下具有不同的行为。这称为多态。

Polymorphism is considered as one of the important features of Object Oriented Programming.
多态被认为是面向对象编程的重要特征之一。

In C++ polymorphism is mainly divided into two types: (在 C++ 中,多态性主要分为两种类型:)

  • Compile time Polymorphism - 编译时多态
  • Runtime Polymorphism - 运行时多态

编译时多态 (Compile time Polymorphism) 或隐式多态是指以不同的 template 参数具体化 function templates 会导致调用不同的函数。函数模板或者类模板的实例化代码生成是在编译期。

运行时多态 (Runtime Polymorphism) 或显式多态是指类中成员函数是 virtual 函数,类将对这些函数表现出运行期多态,也就是说将于运行期根据基类指针或者引用的动态类型决定究竟调用哪一个函数。

还有一种多态就是我们常说的函数重载,它也属于编译期多态,在编译的时候就已经确定了哪个重载函数将被调用。

在这里插入图片描述

polymorphism [,pɒlɪ'mɔːfɪz(ə)m];n. 多态性,多形性,同质多晶

2. Compile time polymorphism - 编译时多态

This type of polymorphism is achieved by function overloading or operator overloading.
这种多态性是通过函数重载或运算符重载来实现的。

2.1 Function Overloading - 函数重载

When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.
如果有多个具有相同名称但参数不同的函数,则称这些函数为重载。可以通过更改参数数量或/和更改参数类型来重载函数。

Rules of Function Overloading - 函数重载规则

//============================================================================
// Name        : function overloading
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Qiang
{
public:

	// function with 1 int parameter
	void func(int x)
	{
		cout << "value of x is " << x << endl;
	}

	// function with same name but 1 double parameter
	void func(double x)
	{
		cout << "value of x is " << x << endl;
	}

	// function with same name and 2 int parameters
	void func(int x, int y)
	{
		cout << "value of x and y is " << x << ", " << y << endl;
	}
};

int main()
{

	Qiang obj;
	int a = 9;
	int b = 3;
	double c = 1.258;

	// Which function is called will depend on the parameters passed.
	// The first 'func' is called
	obj.func(a);

	// The second 'func' is called
	obj.func(c);

	// The third 'func' is called
	obj.func(a, b);

	return 0;
}

value of x is 9
value of x is 1.258
value of x and y is 9, 3

In the above example, a single function named func acts differently in three different situations which is the property of polymorphism.
在上面的示例中,名为 func 的单个函数在三种不同情况下的行为不同,这是多态性的属性。

2.2 Operator Overloading - 运算符重载

C++ also provide option to overload operators. For example, we can make the operator (+) for string class to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So a single operator + when placed between integer operands , adds them and when placed between string operands, concatenates them.
C++ 还提供了重载运算符的选项。例如,我们可以使字符串类的运算符 (+) 连接两个字符串。我们知道这是加法运算符,其任务是将两个操作数相加。因此,单个运算符 + 放在整数操作数之间时,将它们相加,而放在字符串操作数之间时,则将它们连接起来。

//============================================================================
// Name        : operator overloading
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Complex
{
private:
	int real, imag;

public:
	Complex(int r = 0, int i = 0)
	{
		real = r;
		imag = i;
	}

	// This is automatically called when '+' is used with between two Complex objects
	Complex operator +(Complex const &obj)
	{
		Complex res;
		res.real = real + obj.real;
		res.imag = imag + obj.imag;
		return res;
	}

	void print()
	{
		cout << real << " + i" << imag << endl;
	}
};

int main()
{
	Complex c1(10, 5), c2(2, 4);
	Complex c3 = c1 + c2; // An example call to "operator+"
	c3.print();

	return 0;
}

12 + i9

In the above example the operator + is overloaded. The operator + is an addition operator and can add two numbers (integers or floating point) but here the operator is made to perform addition of two imaginary or complex numbers.
在上面的示例中,运算符 + 被重载。运算符 + 是加法运算符,可以将两个数字 (整数或浮点数) 相加,但此处使该运算符执行两个虚数或复数的加法运算。

3. Runtime polymorphism - 运行时多态

This type of polymorphism is achieved by Function Overriding.
这种多态性是通过函数覆盖实现的。

Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
另一方面,当派生类为基类的成员函数之一定义时,就会发生函数覆盖。That base function is said to be overridden.

//============================================================================
// Name        : function overriding
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Base
{
public:
	virtual void print()
	{
		cout << "print base class." << endl;
	}

	void show()
	{
		cout << "show base class." << endl;
	}
};

class Derived: public Base
{
public:
	// print () is already virtual function in derived class, we could also declared as virtual void print () explicitly.
	void print()
	{
		cout << "print derived class." << endl;
	}

	void show()
	{
		cout << "show derived class." << endl;
	}
};

// main function
int main()
{
	Base *bptr;
	Derived dobj;

	bptr = &dobj;

	// Virtual function, binded at runtime (runtime polymorphism).
	bptr->print();

	// Non-virtual function, binded at compile time.
	bptr->show();

	return 0;
}
print derived class.
show base class.

References

https://www.geeksforgeeks.org/

原创文章 532 获赞 1931 访问量 130万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/105252325