c++面向对象实验一:运算符重载

c++面向对象实验一:运算符重载

一、实验目的

(1)掌握通过运算符重载实现多态性的方法;
(2)学会运算符重载的成员函数法和友元函数法;

二、实验要求

编写如下要求的完整程序:点对象运算符重载
(1)建立点类,包含两个成员变量,分别表示横坐标和纵坐标;
(2)具体要求

  • 重载前置运算符++、–;
  • 重载后置运算符++、–;
  • 主函数:申明点对象,进行前置和后置运算并显示点值。

三、实验步骤

建立了一个点类,包含两个成员变量,分别表示横坐标和纵坐标。
重载运算符“+”、“-”为类的成员函数。 然后在main函数中实例化类的2个对象,并利用重载的运算符对其进行计算

四、源码

#include
using namespace std;
class AB
{
public:
    AB(int xx, int yy);
    void ShowAB();
    AB& operator ++();
    AB operator ++(int);
    AB& operator --();
    AB operator --(int);
private:
    int x1,x2;
};
AB::AB(int xx, int yy)
{
    x1=xx;
    x2=yy;
}
void AB::ShowAB()
{
    cout<" , "<operator ++()
{
    x1++;
    x2++;
    return *this;
}
AB AB::operator ++(int)
{
    AB old=*this;
    ++(*this);
    return old;
}
AB& AB::operator --()
{
    x1--;
    x2--;
    return *this;
}
AB AB::operator --(int)
{
    AB old=*this;
    --(*this);
    return old;
}

int main(void)
{
    AB AA(0,0);
    AB BB(0,0);
    cout<<"A的值为:";
    AA.ShowAB();
    cout<<"B的值为:";
    BB.ShowAB();
    cout<<"B=A++运算后,A的值为:";
    (++AA).ShowAB();
    cout<<"             B的值为:";
    (BB++).ShowAB();
    cout<<"B=++A运算后,A的值为:";
    (++AA).ShowAB();
    cout<<"             B的值为:";
    (++BB).ShowAB();

    cout<<"B=A--运算后,A的值为:";
    (--AA).ShowAB();
    cout<<"             B的值为:";
    (BB--).ShowAB();
    cout<<"B=--A运算后,A的值为:";
    (--AA).ShowAB();
    cout<<"             B的值为:";
    (--BB).ShowAB();

    return 0;
} 

五、总结

需要注意区分前置和后置运算符的区别:前置运算符先运算后返回;后置运算符先返回后运算。这点很重要。通过这次实验,我基本掌握了通过运算符重载实现多态性的方法,学会了运算符重载的成员函数法和友元函数法,基本能够区分单目运算符的前置与后置。

你可能感兴趣的:(c/c++,c语言,实验报告)