vectorint.hpp
#pragma once #include<iostream> using std::cout; using std::endl; class vectorint{ private: int size; int *p; public: vectorint(int n):size{n}{ cout<<"constructor 1 called"<<endl; p= new int[n]; } vectorint(int n,int x):size{n}{ cout<<"constructor 2 called"<<endl; p=new int[n]; for(auto i=0;i<n;i++){ p[i]=x; } } vectorint(const vectorint &vp):size{vp.size}{ cout<<"copy constructor called"<<endl; p=new int[size]; for(auto i=0;i<size;i++){ p[i]=vp.p[i]; } } ~vectorint(){ cout<<"destructor called"<<endl; delete[]p; } int &at(int i){ return p[i]; } friend void output(vectorint &x){ cout<<x.at(0); for(auto i=1;i<x.size;i++){ cout<<","<<x.at(i); } cout<<endl; } };
task5.cpp
#include<iostream> #include"vectorint.hpp" void test(){ using namespace std; int n; cin>>n; vectorint x1(n); for(auto i=0;i<n;i++){ x1.at(i)=i*i; } output(x1); vectorint x2(n,42); vectorint x3(x2); output(x2); output(x3); x2.at(0)=77; output(x2); output(x3); } int main(){ test(); }
matrix.hpp
#pragma once #include<iostream> using std::cout; using std::endl; class matrix{ private: int lines; int cols; double *p; public: matrix(int n):lines{n},cols{n}{ p=new double[n*n]; } matrix(int n,int m):lines{n},cols{m}{ p=new double[n*m]; } double &at(int i,int j){ return p[i*cols+j]; } matrix(const matrix &x):lines{x.lines},cols{x.cols}{ p=new double[lines*cols]; for(auto i=0;i<lines;i++){ for(auto j=0;j<cols;j++){ p[i*cols+j]=x.at(i,j); } } } ~matrix()=default; void set(const double *pvalue){ for(int i=0;i<lines*cols;i++){ p[i]=pvalue[i]; } } void set(int i,int j,int value){ p[i*cols+j]=value; } double at(int i,int j)const{ return p[i*cols+j]; } int get_lines()const{ return lines; } int get_cols()const{ return cols; } void print()const{ for(auto i=0;i<lines;i++){ for(auto j=0;j<cols;j++){ cout<<p[i*cols+j]<<" "; } cout<<endl; } } };
task6.cpp
#include <iostream> #include "matrix.hpp" void test() { 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(); } int main() { test(); }
标签:std,matrix,int,cols,实验,using,include From: https://www.cnblogs.com/dgfhdrth/p/16854925.html