实验目的:
- 理解多态的概念、类型及作用
- 掌握运算符重载为成员函数和友元函数的方法
- 理解虚函数的作用和用法
- 了解抽象类
- 使学生能够对使用多态机制的简单程序写出程序结果;
实验环境:
- 所需硬件环境为微机
- 所需软件环境为 MicrosoftVisualC++6.0 或 Code
[实验任务二]:
对类Point(要求Point类有构造函数,能查看坐标的成员函数,及两个表示坐标的数据成员)重载++(自增),--(自减)运算符,要求同时重载前缀和后缀的形式
实验要求:
1.注意加上必要的输入输出提示;
2.注意开头的标注部分,加上自己的姓名以及修改日期;
3.在主函数中对这些运算符重载的调用。
#include <iostream>
using namespace std;
class Point
{
private:
int a, b, x, y;
public:
Point(int a, int b) {
x = a;
y = b;
}
void showPoint();
Point& operator++(); //前置
Point operator++ (int); //后置
Point& operator--(); //前置
Point operator--(int); //后置
~Point() { } //析构函数
};
Point& Point::operator++()//前置++
{
++x, ++y;
return *this;
}
Point Point::operator++(int)//后置++
{
x++, y++;
return *this;
}
Point& Point::operator--()//前置--
{
--x, --y;
return *this;
}
Point Point::operator--(int)//后置--
{
x--, y--;
return *this;
}
void Point::showPoint()
{
cout << "x=" << x << " y=" << y << endl;
}
int main()
{
Point p(2, 3);
p.showPoint();
cout << "前置++:";
++p;
p.showPoint();
cout << "后置++:";
p++;
p.showPoint();
cout << "前置--:";
--p;
p.showPoint();
cout << "后置--:";
p--;
p.showPoint();
return 0;
}
[实验任务三]:
对类Point(要求Point类有构造函数,能查看坐标的成员函数,及两个表示坐标的数据成员),为其定义友元函数实现重载“+”。
实验要求:
1.注意加上必要的输入输出提示;
2.注意开头的标注部分,加上自己的姓名以及修改日期;
3.在主函数中对这些运算符重载的调用。
源程序清单及结果截图:
#include <iostream>
using namespace std;
class Point
{
private:
int a, b, x, y;
public:
Point(int a, int b) {
x = a;
y = b;
}
void showPoint();
friend Point operator+(Point& pt, int nOffset);
friend Point operator+(int nOffset, Point& pt);
~Point() { } //析构函数
};
Point operator+(Point& pt, int nOffset)
{
Point p = pt;
p.x += nOffset;
p.y += nOffset;
return p;
}
Point operator+(int nOffset, Point& pt)
{
Point p = pt;
p.x += nOffset;
p.y += nOffset;
return p;
}
void Point::showPoint()
{
cout << "x=" << x << " y=" << y << endl;
}
int main()
{
Point p(2, 3);
p.showPoint();
p = p + 5;
p.showPoint();
p = p + 10;
p.showPoint();
return 0;
}