#include<iostream> #include<cassert> using std::cout; using std::endl; class vectorInt { public: vectorInt(int n, int m); vectorInt(int n); vectorInt(const vectorInt& a); ~vectorInt(); friend void output(vectorInt&p1); int& at(int index); private: int size; int* p; }; vectorInt::vectorInt(int n) :size(n) { cout << "constructor 1 called." << endl; p = new int[size]; int m = 1; for (int i = 0; i < size; i++) { p[i] = m; } }; vectorInt::vectorInt(int n, int m) :size(n) { p = new int[size]; for (int i = 0; i < size; i++) { p[i] = m; } }; vectorInt::vectorInt(const vectorInt& a) :size{ a.size } { cout << "constructor 2 called." << endl; cout << "copy constructor called." << endl; p = new int[size]; for (int i = 0; i < size; i++) { p[i] = a.p[i]; } } vectorInt::~vectorInt() { delete[] p; } void output(vectorInt& p1) { int*p = p1.p; for (int i = 0; i < p1.size; i++) { cout << p[i] <<" "; } cout << endl; } inline int& vectorInt::at(int index) { assert(index >= 0 && index < size); return p[index]; }
#include <iostream> #include <cassert> using namespace std; class Matrix { public: Matrix(int n); // 构造函数,构造一个n*n的矩阵 Matrix(int n, int m); // 构造函数,构造一个n*m的矩阵 Matrix(const Matrix& X); // 复制构造函数,使用已有的矩阵X构造 ~Matrix(); //析构函数 void set(const double* pvalue); // 用pvalue指向的连续内存块数据为矩阵赋值 void set(int i, int j, int value); //设置矩阵第i行第j列元素值为value double& at(int i, int j); //返回矩阵第i行第j列元素的引用 double at(int i, int j) const; // 返回矩阵第i行第j列元素的值 int get_lines() const; //返回矩阵行数 int get_cols() const; //返回矩列数 void print() const; // 按行打印输出矩阵 private: int lines; // 矩阵行数 int cols; // 矩阵列数 double* p; // 指向存放矩阵数据的内存块的首地址 }; // 类Matrix的实现:待补足 Matrix::Matrix(int n) :lines{ n }, cols{ n } { p = new double[n * n]; } inline Matrix::Matrix(int n, int m) : lines(n), cols(m) { p = new double[n * m]; } inline Matrix::Matrix(const Matrix& X) : lines{ X.lines }, cols{ X.cols } { p = new double[lines * cols]; for (int i = 1; i <= lines * cols; i++) p[i] = X.p[i]; } inline Matrix::~Matrix() { delete[]p; } inline void Matrix::set(const double* pvalue) { for (int i = 0; i < lines * cols; i++) p[i] = pvalue[i]; } inline void Matrix::set(int i, int j, int value) { p[i * cols + j] = value; } inline double& Matrix::at(int i, int j) { return p[i * cols + j]; } inline double Matrix::at(int i, int j) const { return p[i * cols + j]; } inline int Matrix::get_lines() const { return lines; } inline int Matrix::get_cols() const { return cols; } inline 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; }
标签:const,Matrix,int,矩阵,cols,实验,vectorInt From: https://www.cnblogs.com/lhf123/p/16867611.html