第8章 虚函数与多态性
一、实训目的
1.掌握运算符重载的方法;
2.学习使用虚函数实现动态多态性;
二、实训内容
1.公有继承 —— 学生信息类
掌握运算符重载的方法;
2.摩托车类
学习使用虚函数实现动态多态性。
三、实训所实现系统主要功能
1.坐标计算
重载运算符Point p,p++,++p,p–,–p
2.摩托车类
输出把基类中 Run、Stop 声明为虚函数,进行测试
四、实训系统核心代码及必要说明
1.坐标计算
#include <iostream>
using namespace std;
class Point
{
int _x, _y;
public:
Point(int x=0, int y=0) : _x(x), _y(y) {}
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
friend ostream& operator << (ostream& o, const Point& p);
};
/********** Begin **********/
Point& Point :: operator++()
{
_x++; _y++;
return *this;
}
Point Point :: operator++(int)
{
Point t = *this;
++(*this);
return t;
}
Point& Point :: operator--()
{
_x--; _y--;
}
Point Point :: operator--(int)
{
Point t = *this;
--(*this);
return t;
}
/********** End **********/
ostream& operator << (ostream& o, const Point& p) {
o << '(' << p._x << ", " << p._y << ')';
return o;
}
int main()
{
int x,y;
cin>>x>>y;
Point p(x, y);
cout << p << endl;
cout << p++ << endl;
cout << ++p << endl;
cout << p-- << endl;
cout << --p << endl;
return 0;
}
2.摩托车类
#include <iostream>
using namespace std;
/********** Begin **********/
class Vehicle
{
public:
virtual void Run(){
cout << "vehicle run!" << "\n";
}
virtual void Stop(){
cout << "vehicle stop!" << "\n";
}
};
class Bicycle : virtual public Vehicle
{
public:
void Run(){
cout << "bicycle run!" << "\n";
}
void Stop(){
cout << "bicycle stop!" << "\n";
}
};
class Motorcar : virtual public Vehicle
{
public:
void Run(){
cout << "motocar run!" << "\n";
}
void Stop(){
cout << "motocar stop!" << "\n";
}
};
/********** End **********/
class Motorcycle : public Bicycle, public Motorcar
{
public:
void Run() {cout << "motocycle run!" << endl;}
void Stop() {cout << "motocycle stop!" << endl;}
};
int main()
{
Vehicle v;
v.Run();
v.Stop();
Bicycle b;
b.Run();
b.Stop();
Motorcar m;
m.Run();
m.Stop();
Motorcycle mc;
mc.Run();
mc.Stop();
Vehicle* vp = &v;
vp->Run();
vp->Stop();
vp = &b;
vp->Run();
vp->Stop();
vp = &m;
vp->Run();
vp->Stop();
vp = &mc;
vp->Run();
vp->Stop();
return 0;
}