实验3:C++多态编程——实验任务二+三

实验目的:

  1. 理解多态的概念、类型及作用
  2. 掌握运算符重载为成员函数和友元函数的方法
  3. 理解虚函数的作用和用法
  4. 了解抽象类
  5. 使学生能够对使用多态机制的简单程序写出程序结果;

实验环境:

  1. 所需硬件环境为微机 
  2. 所需软件环境为 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;
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值