代码什么的要哭了 2022-05-02 16:23 采纳率: 67.9%
浏览 54
已结题

operator< 小于符号运算符重载问题,输出结果总是反的是什么原因呢?

输出结果总是是1234,如果想输出1321 samsung message send,应该怎么改动啊,
只改动这一部分的代码


Mobile::Mobile(){}

Mobile::Mobile(char *t,int c, int n):Telephone(n)
{
    strcpy(type,t);
    cost = c;    
}

int operator<(Mobile &x1, Mobile &x2)
{
    if(x1.number < x2. number) return x2.number;
    else return x1.number;
}

源程序如下:


/*程序运行结果为:
1321    samsung message send*/

#include<string.h>
//StudybarCommentBegin
#include<iostream>
using namespace std;
//#include <iostream.h>
class Telephone
{
protected :
    int number;
public:
    Telephone()
    {number=1234;}
    Telephone(int n)
    {number=n;}
    void showNumber()
    {cout<<"my phone number is: "<<number<<endl;}
    void call()
    {cout<<"the phone is calling \n";}
};
class Mobile:public Telephone
{
    char *type = new char[20];
    int cost;
public:
    Mobile();
    Mobile(char *t,int c, int n);   //n-tel,c-cost,t-type 
    void message()
    {
        cout<<number<<"\t"<<type<<"\tmessage send\n ";
    }
    friend int operator<(Mobile &x1,Mobile &x2);
};

//StudybarCommentEnd


Mobile::Mobile(){}

Mobile::Mobile(char *t,int c, int n):Telephone(n)
{
    strcpy(type,t);
    cost = c;    
}

int operator<(Mobile &x1, Mobile &x2)
{
    if(x1.number < x2. number) return x2.number;
    else return x1.number;
}

//StudybarCommentBegin
int main()
{
    Mobile m1;
    Mobile m2("samsung",3500,1321);
    if(m1<m2)
        m1.message();
    else
        m2.message();
}    

//StudybarCommentEnd
  • 写回答

1条回答 默认 最新

  • SmallAntJ 2022-05-02 17:01
    关注

    重载函数需要返回True和False,而不是实际数值,否则if条件一直为True只会执行m1.message(),修改如下:

    int operator<(Mobile &x1, Mobile &x2)
    {
        if(x1.number < x2. number) return 0;
        else return 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月10日
  • 已采纳回答 5月2日
  • 创建了问题 5月2日

悬赏问题

  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能