采用运算符重载的方式,实现IP地址字符串的加,减法。
如192.168.1.23 + 5 = 192.168.1.28,
192.168.32.54 - 9 = 192.168.32.45
![](https://profile-avatar.csdnimg.cn/c8b5e6cb6e0b42aeb8e89bb9dfd2d7b8_yj_ll.jpg!4)
求指点,用运算符重载方法实现
- 写回答
- 好问题 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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报