四、实验结论
1.实验任务1-3
验证性实验。
2.实验任务4
-
vector_int.hpp
#include<iostream> using namespace std; class Vector_int{ public: Vector_int(int n); Vector_int(int n,int value); Vector_int(const Vector_int &y); ~Vector_int(); int &at(int index); void show(); private: int size; int *p; }; Vector_int::Vector_int(int n):size(n) { cout<<"dynamic create vector "<<endl; size=n; p=new int[size]; } Vector_int::Vector_int(int n, int value) { size=n; p=new int [size]; for(int i=0;i<size;i++){ p[i]=value; } } Vector_int::Vector_int(const Vector_int &y) { size=y.size; p=new int[size]; for(int i=0;i<size;i++){ p[i]=y.p[i]; } } Vector_int::~Vector_int() { cout<<"delete..."<<endl; delete p; } int & Vector_int::at(int index) { if(0<=index&&index<size){ return p[index]; } } void Vector_int::show() { for(int i=0;i<size;i++) cout<<p[i]<<' '; cout<<endl; }
-
测试类Vector_int的代码(文件task4.cpp)
#include "Vector_int.hpp" #include<iostream> int main(){ using namespace std ; Vector_int v1=Vector_int(5); Vector_int v2=Vector_int(5,6); Vector_int v3=Vector_int(v2); v2.show(); v3.show(); v2.at(2)=5; v3.at(2)=3; v2.show(); v3.show(); }
-
运行测试结果截图
3.实验任务5
-
类Martrix的定义和实现完整代码(Matrix.hpp)
#include<iostream> using namespace std; class Matrix{ public: Matrix(int n); Matrix(int n,int m); Matrix(const Matrix &x); ~Matrix(); void set(const double * pvalue); void set(int i,int j,double value); double & at(int i,int j) ; double at(int i,int j) const ; int get_lines() const; int get_cols() const; void print() const; private: int lines; int cols; double *p; }; Matrix::~Matrix() {} Matrix::Matrix(int n):lines(n),cols(n){ lines=n; cols=n; p= new double [lines*cols]; } Matrix::Matrix(int n, int m):lines(n),cols(m){ lines=n; cols=m; p= new double [lines*cols]; } Matrix::Matrix(const Matrix &x):lines(x.lines),cols(x.cols){ p= new double [lines*cols]; for(int i=0;i<lines;i++) for(int j=0; j<cols;j++) p[i*cols+j]=x.p[i*x.cols+j]; } void Matrix::set(const double * pvalue) { int num=0; for(int i=0;i<lines;i++) for (int j=0;j<cols;j++) p[i*cols+j]=pvalue[num++]; } void Matrix::set(int i, int j, double value) { p[i*cols+j]=value; } double & Matrix::at(int i, int j) { // if(0<=i&&i<=lines&&0<=j<=cols) return p[i*cols+j]; } double Matrix::at(int i, int j) const { return p[i*cols+j]; } void Matrix::print() const { for(int i=0;i<lines;i++) { for (int j = 0; j < cols; j++) cout << p[i * cols + j] << ' '; cout << endl; } } int Matrix::get_cols() const { return cols; } int Matrix::get_lines() const { return lines; }
-
测试代码(task5.cpp)
#include "Matrix.hpp" #include<iostream> int main(){ using namespace std ; double x[]={1,2,3,4,5,6}; Matrix m1(3,2); m1.set(x); m1.print(); cout<<"the first line is:"<<endl; cout<<m1.at(0,0)<<" "<<m1.at(0,1)<<endl; cout<<endl; Matrix m2(2,3); m2.set(x); m2.print(); cout<<"the first line is:"<<endl; cout<<m2.at(0,0)<<" "<<m2.at(0,1)<<' ' <<m2.at(0,2)<<endl; cout<<endl; Matrix m3(m2); m3.set(0,0,999); m3.print(); }
-
运行测试截图