#include<iostream> using namespace std; class vectorint{ public: vectorint(int l=0){ size=l; cout<<"constructor 1 called\n"<<endl; p=new int[size]; } vectorint(int l,int value){ cout << "constructor 2 called\n"; size=l; p=new int[size]; for(int i=0;i<l;i++){ *(p+i)=value; } } vectorint(vectorint &x){ cout << "copy constructor called\n"; size=x.size; p=new int[size]; for(int i=0;i<size;i++) *(p+i)=x.at(i); } ~vectorint(){ cout<<"Destructor called."<<endl; delete []p; } int &at(int i){ return *(p+i); } int get_size(){ return size; } friend void output(vectorint &x){ for(int i=0;i<x.size-1;i++) cout<<*(x.p+i)<<","; cout<<*(x.p+x.size-1)<<endl; } private: int size; int *p; }; void test() { using namespace std; int n; cin >> n; vectorint x1(n); for(int 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(); }
#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, int 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(int n){ lines=n; cols=n; p=new double[lines*cols]; } Matrix::Matrix(int n, int 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*cols;i++) p[i]=x.p[i]; } Matrix::~Matrix(){ delete []p; } void Matrix::set(const double *pvalue){ for(int i=0;i<lines*cols;i++) p[i]=pvalue[i]; } void Matrix::set(int i,int j,int value){ p[i*cols+j]=value; } double &Matrix::at(int i,int j){ return p[i*cols+j]; } double Matrix::at(int i,int j) const{ return p[i*cols+j]; } int Matrix::get_lines() const{ return lines; } int Matrix::get_cols() const{ return cols; } void Matrix::print() const{ for(int i = 0; i < lines; i ++){ for(int j = 0; j < cols-1; j ++) cout << p[i * cols + j] << ","; cout<<p[i*cols+cols-1]<<endl; } } 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(); }
标签:const,Matrix,int,double,lines,cols,实验 From: https://www.cnblogs.com/czba/p/16860928.html