3. 二进制读写 IP 地址#
点击查看考点
二进制输入输出
请设计在 ip.hpp
中定义一个类 class Ip
, 它记录 IPv4 地址 (0.0.0.0 ~ 255.255.255.255), 你应该用 4 个存放在 private
中的整数在记录数据.
提示
你应该为头文件加上头文件包含保护.
为其实现,
默认构造函数: 默认记录 0.0.0.0.
构造函数: 任意 IPv4 地址, 如果不在范围内则抛出异常
std::invalid_argument
, 为此你需要添加该异常类对应的头文件.setter 和 getter: 为每个数据设置 setter 和 getter.
重载
>>
运算符用于输入: 读取形如xxx.xxx.xxx.xxx
的数据.重载
<<
运算符用于输出: 将数据按xxx.xxx.xxx.xxx
的格式输出, 如果数字不足 3 位, 则在左侧补 0.
点击查看解答参考
1#include "ip.hpp"
2
3#include <fstream>
4#include <iostream>
5#include <string>
6
7auto main() -> int {
8 Ip first;
9 std::cin >> first;
10
11 Ip second;
12 std::cin >> second;
13
14 std::string const filepath{"binary.bin"};
15
16 {
17 std::ofstream ofile{filepath, std::ios_base::binary | std::ios_base::out};
18 ofile.write(reinterpret_cast<char const*>(&first), sizeof(first));
19 ofile.write(reinterpret_cast<char const*>(&second), sizeof(second));
20 } // ofstream 的析构函数自动调用 close(), 保证输出已经从缓冲区实际输出进文件中
21
22 {
23 std::ifstream ifile{filepath, std::ios_base::binary | std::ios_base::in};
24 ifile.read(reinterpret_cast<char*>(&first), sizeof(first));
25 ifile.read(reinterpret_cast<char*>(&second), sizeof(second));
26 }
27
28 second.set_fourth(0);
29
30 std::cout << first << '\n';
31 std::cout << second << '\n';
32}