Copyright (c) 2016,烟台大学计算机学院.
All rights reserced.
文件名称:test.cpp
作者 :秦通
完成日期:2016.4.21
版本号 :Codeblocks
问题描述:设计一个IP地址类,用于保存IP地址,并实施在IP地址上一些操作。
程序输入:
#include <iostream>
using namespace std;
class IP
{
private:
union
{
struct
{
unsigned char seg0;
unsigned char seg1;
unsigned char seg2;
unsigned char seg3;
};
unsigned int address;
};
public:
IP(int=0,int=0,int=0,int=0);
void showIP();
bool sameSubnet(const IP &ip, const IP &mark);
char whatKind();
};
IP::IP(int seg00,int seg01,int seg02,int seg03)
{
seg3=seg00;
seg2=seg01;
seg1=seg02;
seg0=seg03;
}
void IP::showIP()
{
cout<<int(seg3)<<"."<<int(seg2)<<"."<<int(seg1)<<"."<<int(seg0)<<endl;
return;
}
bool IP::sameSubnet(const IP &ip, const IP &mark)
{
unsigned int a, b;
a=address&mark.address;
b=ip.address&mark.address;
return (a==b);
}
char IP::whatKind()
{
if(seg3<128)
return 'A';
else if(seg3<192)
return 'B';
else if(seg3<224)
return 'C';
else if(seg3<240)
return 'D';
else
return 'E';
}
int main()
{
IP ip1(202,194,116,97), ip2(202,194,119,102), mark(255,255,248,0);
cout<<"ip1: ";
ip1.showIP();
cout<<"ip2: ";
ip2.showIP();
if(ip1.sameSubnet(ip2,mark))
cout<<"两个IP在同一子网"<<endl;
else
cout<<"两个IP不在同一子网"<<endl;
cout<<"ip1属于"<<ip1.whatKind()<<"类网络"<<endl;
return 0;
}
运行结果: