实验目的
- 体验模板函数、模板类的编写,从多态角度理解模板函数和模板类(类型作为参数)
- 体验标准I/O流类、文件I/O流类、字符串I/O流类的用法,能正确使用
- 针对问题场景,能正确、合理使用流类库对I/O数据进行格式化和读、写操作
- 训练综合应用类的封装、继承、多态特性及现代C++标准库编写正确、高效、安全代码
实验内容
1.实验任务4
实验代码
Vector.hpp
#pragma once
using std::cout;
using std::endl;
template <typename T>
class Vector
{
private:
int size;
T *p;
public:
Vector(int);
Vector(int, T);
~Vector();
int get_size() const { return size; }
T &at(int index)
{
return p[index];
}
T &operator[](int index)
{
return p[index];
}
Vector(const Vector<T> &);
friend void output(Vector &x)
{
int i;
for (i = 0; i < x.size - 1; i++)
{
cout << x.p[i] << ", ";
}
cout << x.p[i] << endl;
}
};
template <typename T>
Vector<T>::Vector(int n) : size{n}
{
p = new T[n];
}
template <typename T>
Vector<T>::Vector(int n, T x) : size{n}
{
p = new T[n];
for (auto i = 0; i < n; i++)
{
p[i] = x;
}
}
template <typename T>
Vector<T>::~Vector()
{
delete[] p;
}
template <typename T>
Vector<T>::Vector(const Vector<T> &vp) : size{vp.size}
{
p = new T[size];
for (auto i = 0; i < get_size(); i++)
{
p[i] = vp.p[i];
}
}
task4.cpp
#include <iostream>
#include "Vector.hpp"
void test() {
using namespace std;
int n;
cin >> n;
Vector<double> x1(n);
for(auto i = 0; i < n; ++i)
x1.at(i) = i * 0.7;
output(x1);
Vector<int> x2(n, 42);
Vector<int> x3(x2);
output(x2);
output(x3);
x2.at(0) = 77;
output(x2);
x3[0] = 999;
output(x3);
}
int main() {
test();
return 0;
}
测试结果
2.实验任务5
实验代码
task5.cpp
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outFile;
outFile.open("cipher_key.txt");
if (!outFile.is_open())
{
cout << "fail to open data1.dat\n";
return 1;
}
for (int i = 0; i < 27; i++)
{
if (!i)
{
cout << " ";
outFile << " ";
for (int j = 97; j < 123; j++)
{
cout << char(j) << " ";
outFile << char(j) << " ";
}
cout << endl;
outFile << endl;
continue;
}
cout << setiosflags(ios_base::left) << setw(2) << i << " ";
outFile << setiosflags(ios_base::left) << setw(2) << i << " ";
for (int j = i; j < i + 26; j++)
{
cout << setiosflags(ios_base::left) << setw(2) << char(65 + j % 26);
outFile << setiosflags(ios_base::left) << setw(2) << char(65 + j % 26);
}
cout << endl;
outFile << endl;
}
outFile.close();
return 0;
}
测试结果
实验总结
模板类和文件操作基本掌握,继承和多态希望还能再练练。
标签:文件,int,Vector,实验,output,include,模板,size From: https://www.cnblogs.com/PhantomGmc/p/16938785.html