# 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;
}

posted on 2019-10-27 23:14  我喜欢宁宁宁  阅读(157)  评论(0编辑  收藏  举报