# 作业题目：请大家结合教材和MOOC资源完成重载与多态的学习，以及相关的验证实验设计！

 定义

 举例运算符重载（对已有的运算符赋予多重含义，使同一个运算符作用于不同类型的数据时导致不同的行为）
 #include using namespace std;

class Box
{
private:
double length;
double width;
double height;
public:
double getV()
{
return length * width * height;
}
void setLength(double len)
{
length = len;
}

void setBreadth(double bre)
{
width = bre;
}

void setHeight(double hei)
{
height = hei;
}
Box operator+(const Box& b)    // 重载 + 运算符，把两个 Box的长、宽、高分别相加
{
Box box;
box.length = this->length + b.length;
box.width = this->width + b.width;
box.height = this->height + b.height;
return box;
}


};

int main()
{
Box Box1;
Box Box2;
Box Box3;
double volume = 0.0;

Box1.setLength(9);
Box1.setHeight(3.0);

Box2.setLength(6.0);
Box2.setHeight(7.0);

volume = Box1.getV();
cout << "Volume of Box1 : " << volume << endl;

volume = Box2.getV();
cout << "Volume of Box2 : " << volume << endl;

Box3 = Box1 + Box2;    //重载+的运用

volume = Box3.getV();
cout << "Volume of Box3 : " << volume << endl;

return 0;


}

<table>
<tr><td bgcolor=#00ffff>测试结果</front></td>
</tr>
</table>
![](https://img2018.cnblogs.com/blog/1784287/201910/1784287-20191027220142515-1809278253.png)
<font color=black size=6 face="黑体">这儿将“+”运算符重载为两个长方体的长、宽、高分别相加，而需要运算的两项也被定义为长方体。</front>

<table>
<tr><td bgcolor=#00ffff>举例多态</front></td>
</tr>
</table>


# include

using namespace std;

class Mammal
{
public:
Mammal()
{
cout << "Mammal" << endl;
}
virtual void speak()
{
cout << "Mammal speak" << endl;
}
};

class Dog :public Mammal
{
public:
Dog()
{
cout << "Dog" << endl;
}
void speak()
{
cout << "Dog speak" << endl;
}
};

void main()
{
Mammal p;
p = new Dog;
p->speak();
(
p).speak();
}

![](https://img2018.cnblogs.com/blog/1784287/201910/1784287-20191027222755155-553558989.png)

<font color=black size=6 face="黑体">被调用的函数必须是虚函数，也就是说必须要在两个产生多态的函数前面加virtual关键字。</front>
<font color=black size=6 face="黑体">调用函数的形参对象必须是基类对象，这里是因为派生类只能给基类赋值，会发生切片操作。基类不能给派生类赋值。</front>

<table>
<tr><td bgcolor=#00ffff>感觉</front></td>
</tr>
</table>

posted @ 2019-10-27 22:28  小囡囡不成仙  阅读(101)  评论(0编辑  收藏  举报