实验五
vectorint.h
#pragma once #include<iostream> using namespace std; class vectorInt { public: int s, * p; vectorInt(int m) { p = new int [m]; s = m; cout << "constructor 1 called." << endl; } vectorInt(int m, int value) { p = new int [m]; s = m; for (int i = 0;i < m;i++) p[i] = value; cout << "constructor 2 called." << endl; } vectorInt(const vectorInt& x) { s = x.s; p = new int[s]; for (int i = 0;i < s;i++) p[i] = x.p[i]; cout << "copy constructor called." << endl; } ~vectorInt() { delete[] p; cout << "destructor called" << endl; } int &at(int m) { return p[m]; } int get_size() { return s; } friend void output(const vectorInt& x) { for (int i = 0;i < x.s;i++) cout << x.p[i] << ","; cout << "\b" <<" " << endl; } };
task
#include <iostream> #include "vectorint.h" 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.h
#pragma once #include <iostream> using std::cout; using std::endl; class Matrix { public: Matrix(int n) { lines = n; cols = n; p = new double[lines * cols]; } Matrix(int n, int m) { lines = n; cols = m; p = new double[lines * cols]; } 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() { delete[] p; } void set(const double* pvalue) { for (int i = 0;i < lines * cols;i++) { p[i] = *pvalue; pvalue++; } } void set(int i, int j, int value) { p[i * cols + j] = value; } double& at(int i, int j) { return p[i * cols + j]; } 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 (int i = 0;i < lines * cols;i++) { cout << p[i] << ","; if ((i+1) % cols == 0) cout << "\b" << " " << endl; } } private: int lines; int cols; double* p; };
task
#include <iostream> #include "Matrix.h" 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/Samapoketto/p/16871032.html