C++语言程序化设计——第五次作业
第八章 多态性
一、多态的概念
1、多态的类型:重载多态、强制多态、包含多态和参数多态
2、多态从实现的角度划分——编译时的多态、运行时的多态
绑定工作在编译连接阶段完成的情况称为静态绑定,绑定工作在程序运行阶段完成的情况称为动态绑定。
二、重载
运算符重载的规则:
(1)只能重载C++中已经有的运算符
(2)重载之后的运算符的优先级和结合性都不会变
(3)重载功能应当与原有功能类似
赋值运算符重载实例:
#include <iostream>
using namespace std;
class Cperson
{
public:
Cperson():_age(0),_weight(0)
{
}
void operator = (int age)//赋值运算符重载
{
this->_age = age;
}
void operator = (double weight)//赋值运算符重载
{
this->_weight = weight;
}
void show()
{
cout << "age = " << _age << endl;
cout << "weight = " << _weight << endl;
}
private:
int _age;
double _weight;
};
int main()
{
Cperson per1;
per1 = 23;
per1 = 68.12;
per1.show();
system("pause");
return 0;
}
运行结果:
三、虚函数
虚函数是动态绑定的基础。虚函数经过派生之后,在类族中就可以实现运行过程中的多态。
代码实例:
#include<iostream>
#include<algorithm>
using namespace std;
class Shape
{
public:
virtual double area()//虚函数
{
return 1.00;
}
};
class Circle :public Shape
{
double r;
public:
Circle(double d) :r(d) {};
double area()//覆盖基类的虚函数
{
return 3.1415926*r*r;
}
};
class Square :public Shape
{
double length;
public:
Square(double l) :length(l) {};
double area()//覆盖基类的虚函数
{
return length * length;
}
};
class Rectangle :public Shape
{
double length, height;
public:
Rectangle(double l, double h) :length(l), height(h) {};
double area()//覆盖基类的虚函数
{
return length * height;
}
};
int main()
{
Shape *p;
double result = 0;
Circle c(3);
Square s(12.2);
Rectangle r(2.3, 5);
p = &c; result += p->area();
p = &s; result += p->area();
p = &r; result += p->area();
cout << "总面积为:" << result << endl;
system("pause");
return 0;
}
运行结果: