第五次作业
重载与多态
1.重载:函数名相同,但是函数参数不同。调用时根据参数的不同决定调用哪一个函数。
2.多态:函数名相同,函数形参也相同。调用时根据函数类型是虚函数还是普通成员函数决定调用哪一个。
3.实现多态的方式:函数重载,运算符重载,虚函数。
(一)
重载前++
#include <iostream>
using namespace std;
class Complex{
private:
int image,real;
public:
Complex(int i=0,int r=0):image(i),real(r){}
Complex &operator++();//重载 前++
void show();
};
Complex &Complex::operator++(){
image++;
real++;
return *this;
}
void Complex::show(){
cout<<"("<<image<<","<<real<<")"<<endl;
}
int main(){
Complex complex(1,1);
++complex;//函数重载了前++
complex.show();
return 0;
}
(二)
多态按字面的意思就是多种形态。当类之间存在层次结构,并且类之间是通过继承关联时,就会用到多态。
C++ 多态意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。下面的实例中,基类 Shape 被派生为两个类,如下所示:
#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;
}
};
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);
}
};
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果
Parent class area
Parent class area
导致错误输出的原因是,调用函数 area() 被编译器设置为基类中的版本,这就是所谓的静态多态,或静态链接 - 函数调用在程序执行前就准备好了。有时候这也被称为早绑定,因为 area() 函数在程序编译期间就已经设置好了。对程序稍作修改,在 Shape 类中,area() 的声明前放置关键字 virtual,如下所示:
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;
}
};