采用运算符重载的方式,实现IP地址字符串的加,减法。
如192.168.1.23 + 5 = 192.168.1.28,
192.168.32.54 - 9 = 192.168.32.45
求指点,用运算符重载方法实现
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 技术专家团-小桥流水 2021-11-03 18:03关注
运行结果及代码如下,如有帮助,请帮忙采纳一下,谢谢。
代码:
#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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 echarts动画效果失效的问题。官网下载的例子。
- ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
- ¥15 Attention is all you need 的代码运行
- ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
- ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
- ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
- ¥30 关于<main>标签页面跳转的问题
- ¥80 部署运行web自动化项目
- ¥15 腾讯云如何建立同一个项目中物模型之间的联系
- ¥30 VMware 云桌面水印如何添加