0%

C++ 多态 :一起看1

2020年3月2日 下午10:30
C++ 多态 | 菜鸟教程

C++多态定义:

  1. C++ 多态意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数

C++实现多态的两个条件:

  1. 继承
  2. 基类使用虚函数声明

总结:

  1. 如果在基类中使用vitual虚函数,::那么编译器看的是指针的内容,而不是它的类型::。
    1. 编译器看的是指针的内容 == > 动态绑定
    2. 编译器看的是类型 == > 静态绑定
    3. 代码指的就是下面的核心句1-2。

基类的定义-1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> 
using namespace std;

class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << “Parent class area :” <<endl;
return 0;
}
};

基类的定义-2:【使用virtual】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> 
using namespace std;

class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << “Parent class area :” <<endl;
return 0;
}
};

继承类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << “Rectangle class area :” <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};

主函数定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 程序的主函数
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// 核心句1:存储矩形的地址
shape = &rec;
// 核心句2:调用矩形的求面积函数 area
shape->area();

return 0;
}