问题及代码:
/*copyright(c)2016.烟台大学计算机学院
* All rights reserved,
* 文件名称:text.Cpp
* 作者:吴敬超
* 完成日期:2016年4月5日
* 版本号:vc++6.0
*
* 问题描述:IP地址类
* 输入描述:
* 程序输出: 输出结果
*/
#include<iostream>
using namespace std;
class IP
{private:
union
{
struct
{
unsigned char seg0;
unsigned char seg1;
unsigned char seg2;
unsigned char seg3;
};
unsigned char address;
};
public:
IP(int=0,int=0,int=0,int=0);//构造函数
void showIP(); //用四段法显示IP地址
bool sameSubnet(const IP &ip, const IP &mark); //判断是否处于同一子网
char whatkind();//返回属于哪一类网络
};
IP::IP(int s0,int s1, int s2,int s3)
{
seg0=s0;
seg1=s1;
seg2=s2;
seg3=s3;
}
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 i1,i2;
i1=address&mark.address;
i2=ip.address&mark.address;
return (i1=i2);
}
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,30);
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;
}
运行结果: