首页 > 其他分享 >实验6 模板类、文件I/O和异常处理

实验6 模板类、文件I/O和异常处理

时间:2024-12-24 12:08:17浏览次数:6  
标签:std 文件 const get Complex 实验 return include 模板

任务1:

task1.cpp

  1 Complex.hpp:
  2 #pragma once
  3 
  4 #include <iostream>
  5 #include <stdexcept>
  6 
  7 // 声明
  8 ////////////////////////////////////////////////////
  9 // 复数模板类声明
 10 template<typename T>
 11 class Complex {
 12 public:
 13     Complex(T r = 0, T i = 0);
 14     Complex(const Complex<T> &c);
 15 
 16     T get_real() const;
 17     T get_imag() const;
 18 
 19     // 重载+=为成员函数
 20     Complex<T>& operator+=(const Complex<T> &c);
 21 
 22     // 重载<<、>>为友元函数
 23     template<typename T1>
 24     friend std::ostream& operator<<(std::ostream &out, const Complex<T1> &c);
 25 
 26     template<typename T1>
 27     friend std::istream& operator>>(std::istream &in, Complex<T1> &c);
 28 
 29 private:
 30     T real, imag;
 31 };
 32 
 33 // 普通函数声明
 34 // 重载+用于Complex类型
 35 template<typename T>
 36 Complex<T> operator+(const Complex<T> &c1, const Complex<T> &c2);
 37 
 38 // 重载==用于Complex类型
 39 template<typename T>
 40 bool operator==(const Complex<T> &c1, const Complex<T> &c2);
 41 
 42 
 43 // 实现
 44 ////////////////////////////////////////////////////
 45 // 成员函数模板实现
 46 template<typename T>
 47 Complex<T>::Complex(T r, T i): real{r}, imag{i} {
 48 }
 49 
 50 template<typename T>
 51 Complex<T>::Complex(const Complex<T> &c): real{c.real}, imag{c.imag} {
 52 }
 53 
 54 template<typename T>
 55 T Complex<T>::get_real() const {
 56     return real;
 57 }
 58 
 59 template<typename T>
 60 T Complex<T>::get_imag() const {
 61     return imag;
 62 }
 63 
 64 // 重载+=为成员函数
 65 template<typename T>
 66 Complex<T>& Complex<T>::operator+=(const Complex<T> &c) {
 67     real += c.real;
 68     imag += c.imag;
 69 
 70     return *this;
 71 }
 72 
 73 ///////////////////////////////////////
 74 // 友元函数模板实现
 75 template<typename T1>
 76 std::ostream& operator<<(std::ostream &out, const Complex<T1> &c) {
 77     if(c.imag >= 0)
 78         out << c.real << " + " << c.imag << "i";
 79     else
 80         out << c.real << " - " << -c.imag << "i";
 81     
 82     return out;
 83 }
 84 
 85 template<typename T1>
 86 std::istream& operator>>(std::istream &in, Complex<T1> &c) {
 87     in >> c.real >> c.imag;
 88 
 89     return in;
 90 }
 91 
 92 ///////////////////////////////////////
 93 // 普通函数模板实现
 94 // 重载+用于Complex类型
 95 template<typename T>
 96 Complex<T> operator+(const Complex<T> &c1, const Complex<T> &c2) {
 97     return Complex<T>(c1.get_real()+c2.get_real(), 
 98                       c1.get_imag()+c2.get_imag());
 99 }
100 
101 // 重载==用于Complex类型
102 template<typename T>
103 bool operator==(const Complex<T> &c1, const Complex<T> &c2) {
104     return c1.get_real() == c2.get_real() && 
105            c1.get_imag() && c2.get_imag();
106 }
107 
108 task1.cpp:
109 #include "Complex.hpp"
110 #include <iostream>
111 #include <fstream>
112 #include <stdexcept>
113 
114 void test1();
115 void test2();
116 
117 int main() {
118     using namespace std;
119 
120     cout << "测试1: 复数模板类测试" << endl;
121     test1();
122 
123     cout << "\n测试2: 文件I/O测试" << endl;
124     test2();
125 }
126 
127 void test1() {
128     using namespace std;
129 
130     Complex<double> c1{3.5, 2}, c2;
131     cout << "Enter c2: ";
132     cin >> c2;
133     cout << "c1 = " << c1 << endl;
134     cout << "c2 = " << c2 << endl;
135     cout << "c1 == c2: " << boolalpha << (c1 == c2) << endl;
136 
137     cout << "c1 + c2 = " << c1 + c2 << endl;
138     c1 += c2;
139     cout << "c1.real = " << c1.get_real() << endl;
140     cout << "c1.imag = " << c1.get_imag() << endl;
141 
142     cout << "c1 == c2: " << boolalpha << (c1 == c2) << endl;
143 }
144 
145 void test2() {
146     using namespace std;
147 
148     Complex<int> c1{1, 2}, c2{9, -7};
149     ofstream out("ans.txt");
150     if(!out.is_open()) {
151         cout << "fail to open file ans.txt to write\n";
152         return;
153     }
154 
155     out << "c1 = " << c1 << endl;
156     out << "c2 = " << c2 << endl;
157     out << "c1 + c2 = " << c1 + c2 << endl;
158     out << "(c1 == c2) = " << boolalpha << (c1 == c2) << endl;
159 
160     out.close();
161     cout << "测试ok!" << endl;
162 }
View Code

任务2:

task2.cpp

  1 Contestant.hpp:
  2 #pragma once
  3 
  4 #include <iostream>
  5 #include <iomanip>
  6 #include <string>
  7 
  8 using std::string;
  9 using std::ostream;
 10 using std::istream;
 11 using std::setw;
 12 using std::setprecision;
 13 using std::setiosflags;
 14 using std::ios_base;
 15 
 16 // Contestant类声明
 17 class Contestant {
 18 public:
 19     Contestant() = default;
 20     ~Contestant() = default;
 21 
 22     int get_num() const { return num; }
 23     float get_time_usage() const { return time_usage; }
 24 
 25     friend ostream& operator<<(ostream &out, const Contestant &c);
 26     friend istream& operator>>(istream &in, Contestant &c);
 27 
 28 private:
 29     string no;          // 学号
 30     string name;        // 姓名
 31     string major;       // 专业
 32     int num;            // 解题数
 33     float time_usage;   // 总用时
 34 };
 35 
 36 // 友元函数实现
 37 // 重载流插入运算符<<
 38 ostream& operator<<(ostream &out, const Contestant &c) {
 39     out << setiosflags(ios_base::left);
 40     out << setw(15) << c.no
 41         << setw(15) << c.name
 42         << setw(15) << c.major
 43         << setw(5) << c.num
 44         << setprecision(2) << c.time_usage;
 45     
 46     return out;
 47 }
 48 
 49 // 重载流提取运算符>>
 50 istream& operator>>(istream &in, Contestant &c) {
 51     in >> c.no >> c.name >> c.major >> c.num >> c.time_usage;
 52 
 53     return in;
 54 }
 55 
 56 utils.hpp:
 57 #include "Contestant.hpp"
 58 #include <fstream>
 59 #include <iostream>
 60 #include <string>
 61 #include <vector>
 62 
 63 // 排序函数
 64 // 按解题数比较,解题数相同的情况下,按总用时比较,总用时越少,排名越靠前
 65 bool compare_by_solutionInfo(const Contestant &c1, const Contestant &c2) {
 66     if(c1.get_num() > c2.get_num())
 67         return true;
 68     
 69     if(c1.get_num() == c2.get_num())
 70         return c1.get_time_usage() < c2.get_time_usage();
 71     
 72     return false;
 73 }
 74 
 75 // 把vector<Constestant>对象中的元素插入到输出流out
 76 void output(std::ostream &out, const std::vector<Contestant> &v) {
 77     for(auto &i: v)
 78         out << i << std::endl;
 79 }
 80 
 81 
 82 // 把vector<Contestant>对象中的元素写到filename文件中
 83 void save(const std::string &filename, std::vector<Contestant> &v) {
 84     using std::ofstream;
 85 
 86     ofstream out(filename);
 87     if(!out.is_open()) {
 88         std::cout << "fail to open file to write\n";
 89         return;
 90     }
 91 
 92     output(out, v);
 93     out.close();
 94 }
 95 
 96 // 从文件filename读取参赛选手信息到vector<Contestant>对象
 97 void load(const std::string &filename, std::vector<Contestant> &v) {
 98     using std::ifstream;
 99 
100     ifstream in(filename);
101     if(!in.is_open()) {
102         std::cout << "fail to open file to read\n";
103         return;
104     }
105 
106     std::string title_line;
107     getline(in, title_line);     // 跳过标题行
108 
109     int first_column;
110     Contestant t;
111     while(in >> first_column >> t) 
112         v.push_back(t);
113 
114     in.close();
115 }
116 
117 
118 task2.cpp:
119 #include "Contestant.hpp"
120 #include "utils.hpp"
121 #include <iostream>
122 #include <vector>
123 #include <algorithm>
124 
125 
126 void test() {
127     using namespace std;
128 
129     vector<Contestant> v;
130 
131     load("data2.txt", v);   // 从文件加载选手信息到对象v
132     sort(v.begin(), v.end(), compare_by_solutionInfo);  // 按解题情况排序
133     output(cout, v);    // 输出对象v中信息到屏幕
134     save("ans.txt", v); // 把对象v中选手信息保存到文件
135 }
136 
137 int main() {
138     test();
139 }
View Code

 

任务3:

task3.cpp

 1 Triangle.hpp:
 2 #include <iostream>
 3 #include <stdexcept>
 4 #include <cmath>
 5 
 6 using namespace std;
 7 
 8 class Triangle {
 9 public:
10     Triangle(double s1, double s2, double s3);
11     ~Triangle() = default;
12 
13     double area() const;
14 
15 private:
16     double a, b, c;
17 };
18 
19 Triangle::Triangle(double s1, double s2, double s3): a{s1}, b{s2}, c{s3} {
20     if(a <= 0 || b <= 0 || c <= 0)
21         throw invalid_argument("边长出现负值");
22         
23     if(a+b <= c || b+c <= a || a+c <= b) 
24         throw invalid_argument("不满足任意两边之和大于第三边");
25 }
26 
27 double Triangle::area() const {
28     double s = (a + b + c)/2;
29     return sqrt(s*(s-a)*(s-b)*(s-c));
30 }
31 
32 task3.cpp:
33 #include "Triangle.hpp"
34 #include <iostream>
35 #include <fstream>
36 
37 void test() {
38     using namespace std;
39 
40     cout << "从文件读入三角形三边边长,计算面积" << endl;
41 
42     ifstream in("data3.txt");
43     if(!in.is_open()) {
44         cout << "fail to open file to read\n";
45         return;
46     }
47 
48     double a,b,c;
49     do {
50         cout << "三角形边长: ";
51         in >> a >> b >> c;
52         cout << a << " " << b << " " << c << endl;
53 
54         try {
55             Triangle t(a, b, c);
56             cout << "三角形面积: " << t.area() << endl << endl;
57         }catch(const exception &e) {
58             cout << "error: " << e.what() << endl << endl;
59         }
60 
61         if(in.peek() == EOF)
62             break;
63     } while(1);
64 
65     in.close();
66 }
67 
68 int main() {
69     test();
70 }
View Code

 

任务4:

task4.cpp

  1 Vector.hpp:
  2 #include<iostream>
  3 
  4 using namespace std;
  5 
  6 template<typename T>
  7 class Vector {
  8 private:
  9     T* ptr;
 10     int size;
 11 public:
 12     Vector(int n) {
 13         if (n < 0) {
 14             throw length_error("Vector constructor: negative size");
 15         }
 16         else {
 17             ptr = new T[n];
 18             size = n;
 19         }
 20     }
 21     Vector(int n, T data) {
 22         if (n < 0) {
 23             throw length_error("Vector constructor: negative size");
 24         }
 25         else {
 26             ptr = new T[n];
 27             size = n;
 28             for (int i = 0; i < size; i++) {
 29                 ptr[i] = data;
 30             }
 31         }
 32     }
 33     Vector(Vector<T>& v) {
 34         size = v.get_size();
 35         ptr = new T[size];
 36         for (int i = 0; i < size; i++) {
 37             ptr[i] = v.at(i);
 38         }
 39     }
 40     int get_size() {
 41         return size;
 42     }
 43     T& at(int index) const {
 44         if (index > size - 1) {
 45             throw overflow_error("Vector: index out of range");
 46         }
 47         return ptr[index];
 48     }
 49     T& operator[](int index) {
 50         if (index > size - 1) {
 51             throw overflow_error("Vector: index out of range");
 52         }
 53         return ptr[index];
 54     }
 55     template<typename T>
 56     friend void output(const Vector<T>& v);
 57 };
 58 
 59 template<typename T>
 60 void output(const Vector<T>& v) {
 61     for (int i = 0; i < v.size; i++) {
 62         cout << v.at(i) << ' ';
 63     }
 64     cout << endl;
 65 }
 66 
 67 task4.cpp:
 68 #include <iostream>
 69 #include "Vector.hpp"
 70 
 71 void test1() {
 72     using namespace std;
 73 
 74     int n;
 75     cout << "Enter n: ";
 76     cin >> n;
 77 
 78     Vector<double> x1(n);
 79     for (auto i = 0; i < n; ++i)
 80         x1.at(i) = i * 0.7;
 81 
 82     cout << "x1: "; output(x1);
 83 
 84     Vector<int> x2(n, 42);
 85     const Vector<int> x3(x2);
 86 
 87     cout << "x2: "; output(x2);
 88     cout << "x3: "; output(x3);
 89 
 90     x2.at(0) = 77;
 91     x2.at(1) = 777;
 92     cout << "x2: "; output(x2);
 93     cout << "x3: "; output(x3);
 94 }
 95 
 96 void test2() {
 97     using namespace std;
 98 
 99     int n, index;
100     while (cout << "Enter n and index: ", cin >> n >> index) {
101         try {
102             Vector<int> v(n, n);
103             v.at(index) = -999;
104             cout << "v: "; output(v);
105         }
106         catch (const exception& e) {
107             cout << e.what() << endl;
108         }
109     }
110 }
111 
112 int main() {
113     cout << "测试1: 模板类接口测试\n";
114     test1();
115 
116     cout << "\n测试2: 模板类异常处理测试\n";
117     test2();
118 }
View Code

 

任务5:

task5.cpp

 1 Student.hpp:
 2 #pragma once
 3 #include<iostream>
 4 using namespace std;
 5 class Student {
 6 public:
 7     Student(string id, string name, string major, int score) {
 8         this->id = id; this->name = name; this->major = major; this->score = score;
 9     }
10     string getId() {
11         return id;
12     }
13     string getName() {
14         return name;
15     }
16     string getMajor() {
17         return major;
18     }
19     int getScore() {
20         return score;
21     }
22     friend bool Compare(Student& s1, Student& s2);
23 private:
24     string id;
25     string name;
26     string major;
27     int score;
28 };
29 bool Compare(Student& s1, Student& s2) {
30     if (s1.major.compare(s2.major) > 0) {
31         return false;
32     }
33     else if (s1.major.compare(s2.major) == 0) {
34         if (s1.score < s2.score) {
35             return false;
36         }
37     }
38     return true;
39 }
40 
41 task5.cpp:
42 #include<iostream>
43 #include"student.hpp"
44 #include<fstream>
45 #include<vector>
46 #include<algorithm>
47 using namespace std;
48 int main() {
49     ifstream fin;
50     fin.open("data5.txt");
51     string lst;
52     for (int i = 0; i < 4; i++) {
53         fin >> lst;
54     }
55     vector<Student> stulist;
56     string id, name, major;
57     int score;
58     while (fin >> id >> name >> major >> score) {
59         stulist.push_back(Student(id, name, major, score));
60     }
61     fin.close();
62     sort(stulist.begin(), stulist.end(), Compare);
63     ofstream fopen;
64     fopen.open("ans.txt");
65     for (auto& stu : stulist) {
66         cout << stu.getId() << " " << stu.getName() << " " << stu.getMajor() << " " << stu.getScore() << endl;
67     }
68 }
View Code

 

标签:std,文件,const,get,Complex,实验,return,include,模板
From: https://www.cnblogs.com/Altairsss/p/18618930

相关文章

  • LFImap:本地文件包含发现和利用工具
    免责声明该公众号分享的安全工具和项目均来源于网络,仅供安全研究与学习之用,如用于其他用途,由使用者承担全部法律及连带责任,与工具作者和本公众号无关。简介:LFImap是一个针对本地文件包含发现和利用的工具,该项目处于预alpha阶段。主要版本1.0即将推出,其中包含大量新功能和模块......
  • 实验6
    test:点击查看代码#pragmaonce#include<iostream>#include<stdexcept>usingnamespacestd;template<typenameT>classVector{public:Vector(intn,intvalue=0);Vector(Vector<T>&v);~Vector();intget_......
  • 最直接真实的药物靶点筛选实验——LiP-MS药物靶点筛选技术
    有限蛋白水解质谱技术(LimitedProteolysisMassSpectrometry,LiP-MS)是研究小分子化合物(天然产物、代谢物等)与蛋白质相互作用,揭示蛋白结构动态变化的高通量质谱筛选技术。本公司推出LiP-MS药物靶点筛选解决方案,包含三种研究目的场景LiP-MS药物靶点筛选:体外生理条件下寻找小分......
  • 实验6 模板类,文件I/O及异常处理
    一实验目的练习编写模板函数、模板类,从多态角度理解模板函数和模板类(类型作为参数)体验标准I/O流类、文件I/O流类、字符串I/O流类的用法,能正确使用针对问题场景,使用流类库对I/O数据进行格式化和读、写操作体验异常处理的基础用法,能解释异常处理的机制和流程训练综合应用类的......
  • 面向教学科研智能网联汽车仿真测试实验室
    概述    随着智能网联汽车的蓬勃发展,高校培养相关人才的需求日益迫切。然而,传统教学设备难以满足实际工程应用需求,限制了学生实践能力和科研创新。为此,经纬恒润推出高校智能网联汽车仿真测试解决方案,为高校提供与产业接轨的全栈式解决方案,助力科研项目、人才培养和教学模......
  • 软件项目《光灵斗域》实验报告
    软件项目《光灵斗域》实验报告分工:陈艺根:卡牌效果,卡牌逻辑,随机地图设计,UI框架,音频管理王朗凡:游戏策划,游戏背包UI肖宇轩:游戏中数据处理袁瑶:美术,场景过渡的代码夏亦轩:TA,着色器编程,地图设计,敌人设计相关文档游戏网页光灵斗域PC/主机-TapTap策划案https://bxqu4udvl43.fe......
  • Flutter OHOS open_filex(以字符串结果打开文件)
    open_filex以字符串结果打开文件的插件用法要使用此插件,请在pubspec.yaml文件中添加open_filex作为依赖项。dependencies:open_filex:^lastVersion例子import'package:open_filex/open_filex.dart';OpenFilex.open("/sdcard/example.txt");鸿蒙OS代码文件是否......
  • 文件系统
    文件系统文件系统是小程序提供的一套以小程序和用户维度隔离的存储以及一套相应的管理接口。通过wx.getFileSystemManager()可以获取到全局唯一的文件系统管理器,所有文件系统的管理操作通过FileSystemManager来调用。varfs=wx.getFileSystemManager()文件主要分为两大......
  • C#队列、多线程根据URL下载文件
    ///<summary>///下载辅助类///</summary>publicclassDownFileHelper{///<summary>///构造函数///</summary>staticDownFileHelper(){Start();}privatestaticobjectlockObject=newobject();......
  • 这款跨网文件安全交换系统 凭什么受到各行业的欢迎?
    跨隔离网的文件传输交换,这是各个行业都会面临的场景,能解决传输问题的工具也不少,可为什么说有一款跨网文件安全交换系统,在各行业中应用都很广泛,受到各行业的欢迎呢?首先我们来看看跨网文件传输有哪些需求。 一、跨网文件传输的普遍需求跨网文件传输的普遍需求与挑战可以概括为以......