柒樂葉 2021-11-03 17:38 采纳率: 100%
浏览 33
已结题

求指点,用运算符重载方法实现

采用运算符重载的方式,实现IP地址字符串的加,减法。
如192.168.1.23 + 5 = 192.168.1.28,
192.168.32.54 - 9 = 192.168.32.45

  • 写回答

2条回答 默认 最新

  • 关注

    运行结果及代码如下,如有帮助,请帮忙采纳一下,谢谢。

    img

    代码:

    #include <iostream>
    #include <string>
    using namespace std;
    
    class ipaddr
    {
    private:
        string mip[4];
    public:
        ipaddr(string ip)
        {
            string t;
            int pos = ip.find('.');
            mip[0] = ip.substr(0,pos);
            t = ip.substr(pos+1,ip.length()-pos);
    
            pos = t.find('.');
            mip[1] = t.substr(0,pos);
            t = t.substr(pos+1,t.length() - pos);
    
            pos = t.find('.');
            mip[2] = t.substr(0,pos);
            t = t.substr(pos+1,t.length() - pos);
    
            mip[3]=t;
        }
    
        ipaddr& operator+(const int n){ //如果参数是const char*类型的话,就多一个类型转换,用atoi把字符串转成数字就可以了
            char buf[4]={0};
            int nb = atoi(mip[3].c_str());
            nb += n;
            nb = nb%255; //大于255后取余
            mip[3] = itoa(nb,buf,10);
            return *this;
        }
    
        ipaddr& operator-(const int n){
            char buf[4]={0};
            int nb = atoi(mip[3].c_str());
            nb -= n;
            if(nb < 0) nb+=255;
            nb = nb%255; //大于255后取余
            mip[3] = itoa(nb,buf,10);
            return *this;
        }
        
        void show()
        {
            cout << mip[0] <<"." << mip[1] <<"." << mip[2] <<"." <<mip[3]<<endl;
        }
    
    };
    
    
    
    int main()
    {
        ipaddr ip("192.168.0.24");    
        ip = ip - 5;
        ip.show();
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 11月3日
  • 已采纳回答 11月3日
  • 创建了问题 11月3日

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了