代码什么的要哭了 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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵