采用运算符重载的方式,实现IP地址字符串的加,减法。
如192.168.1.23 + 5 = 192.168.1.28,
192.168.32.54 - 9 = 192.168.32.45
运行结果及代码如下,如有帮助,请帮忙采纳一下,谢谢。
代码:
#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;
}
那要是192.168.32.01-14该怎么处理?只需要重载末位加减么?