面向对象实验二(运算符重载)

本文通过定义空间点类和复数类,展示了如何使用成员函数和友元函数重载运算符,包括前缀和后缀递增递减运算符及等于运算符。并通过主函数演示了这些类的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、实验目的
1、掌握成员函数重载运算符。
2、掌握友元函数重载运算符。
3、理解并掌握引用在运算符重载中的作用。


二、实验内容

1、定义空间中的点类(有x,y,z坐标),并重载其++和—运算符。编写主函数对该类进行应用。

#include<iostream>
using namespace std;

class Point
{
private:
    int x,y,z;
public:
    Point(int a=0,int b=0,int c=0);
    Point operator ++();
    Point operator ++(int);
    Point operator --();
    Point operator --(int);
    void print();
};

int main()
{
    Point ob1(2,3,4),ob2;
    ++ob1;
    ob1.print();
    ob2=ob1++;
    ob2.print();
    ob1.print();
    --ob1;
    ob1.print();
    ob2=ob1--;
    ob2.print();
    ob1.print();
    return 0;
}


Point::Point(int a, int b,int c)
{
    x=a;
    y=b;
    z=c;
}

void Point::print()
{
    cout<<'('<<x<<','<<y<<','<<z<<')'<<endl;
}

Point Point::operator ++()
{
    ++x;
    ++y;
    ++z;
    return *this;
}

Point Point::operator ++(int)
{
    Point temp=*this;
    x++;
    y++;
    z++;
    return temp;
}

Point Point::operator --()
{
    --x;
    --y;
    --z;
    return *this;
}

Point Point::operator --(int)
{
    Point temp=*this;
    x--;
    y--;
    z--;
    return temp;
}

2、定义一个复数类,并通过定义运算符重载实现两个复数可以判别是否相等(==),并给出主函数应用该类。

#include<iostream>
#include<iomanip>
using namespace std;

class com
{
    private:
    int real,imag;
    public:
    com(int a,int b);
    void operator ==(com b);
};



int main()
{
    com ob1(2.2,3.3),ob2(2.2,3.3);
    ob1==ob2;
    return 0;
}

com::com(int a,int b)
{
    real=a;
    imag=b;
}

void com::operator ==(com b)
{
    if((real==b.real)&&(imag==b.imag))
    {
        cout<<"两复数相等!!"<<endl;
    }
    else
    {
        cout<<"两复数不相等!!"<<endl;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值