对 复数集合 一题代码的讲解

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stdio.h>
using namespace std;

class Complex
{
public:
    double Re;
    double Im;
    double mo;
    void Input()
    {
        scanf("%lf+i%lf",&Re,&Im);
        mo = sqrt(Re*Re + Im*Im);
    }
    void Show() const
    {
        printf("%.0lf+i%.0lf\n",Re,Im);
    }

    bool operator < ( const Complex &c2) const
    {
        if(this->mo != c2.mo)
            return this->mo<c2.mo;
        else
            return this->Im>c2.Im;
    }
};
int main()
{
    int n,i;
    string temp;
    cin>>n;
    priority_queue<Complex,vector<Complex>,less<Complex> >q;
    string Pop = "Pop",Insert = "Insert";
    for(i=0;i<n;i++)
    {
        cin>>temp;
        if(temp == Insert)
        {
            Complex temp;
            temp.Input();
            q.push(temp);
            cout<<"SIZE = "<<q.size()<<endl;
        }
        else
        {
            if(q.empty())
                cout<<"empty"<<endl;
            else
            {
                q.top().Show();
                q.pop();
                cout<<"SIZE = "<<q.size()<<endl;
            }

        }
    }
    return 0;
}

一、类中重载运算符

一般有两种方法,一是定义一个友元函数,参数为两个类对象。

二是用此方法,模板是:

    返回值类型 operator @ (参数列表)

{

}

   如果是一个双目运算符(需要两个类的对象参与的),在参数列表里需要添加另一个类的对象。

    例如本题中:

    bool operator < ( const Complex &c2) const

    在执行 c1 < c2时,相当于将 c2 作为参数传入到了该成员函数中。

    另一个参数使用引用类型

    const表示此函数不会对类的属性进行修改,如果要使用优先队列等容器时要加上const。

二、类在优先队列中的使用

        priority_queue<Complex,vector<Complex>,less<Complex> >q;

          重载运算符时 属性必须加上const

        方法和基本类型相同,该类必须重载<,>运算符才能使用优先队列。

        重载<可使用less,重载>可使用greater;

三、对于const的一点理解

        对于定义为const的变量,是不允许对其进行修改的。同理,对于类中定义为const的成员函数,不允许其对类的属性进行修改,所以在定义类的成员函数时,如果该函数未对类进行修改,尽量在成员函数定义后加上const。

        同时,定义为const的类的变量,只能调用类中定义为const的成员函数。

         在本例中,一开始Show()函数未定义为const属性,q.top().Show()会报错,因为top()返回的是一个const引用,无法调用Show()函数,将Show()属性改为const后即可正常使用.

        

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值