vector_int.hpp
#ifndef vector_int_hpp
#define vector_int_hpp
#include <cstdio>
#include <iostream>
using namespace std;
class Vector_int
{
private:
int size;
int *p;
public:
int& at(int x){
return p[x];
}
Vector_int(int size, int y = 0.0) : size(size)
{
cout << "Build a new class size = " << size << " , value = " << y << "\n";
p = new int[size];
for (int i = 0; i < size; ++i)
{
p[i] = y;
}
}
Vector_int(const Vector_int &X)
{
cout << "Build a new class size = " << X.size << " , value = " << X.p[0] << "\n";
p = new int[X.size];
size = X.size;
for (int i = 0; i < X.size; ++i)
{
p[i] = X.p[i];
}
}
~Vector_int()
{
cout << "Delete the class size = " << size << " , value = " << p[1] << "\n";
delete[] p;
}
};
#endif
task4.cpp
#include<iostream>
#include<cstdio>
#include"vector_int.hpp"
using namespace std;
int main()
{
Vector_int x(10);
puts("");
Vector_int y(10,6);
puts("");
Vector_int z(y);
puts("");
y.at(0)=999;
return 0;
}
Matrix.hpp
#ifndef Matrix_H
#define Matrix_H
#include <iostream>
using namespace std;
class Matrix
{
private:
int lines, 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];
}
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 *X)
{
for (int i = 0; i < lines * cols; i++)
{
p[i] = X[i];
}
};
void set(int i, int j, int value)
{
if (i >= 0 && i < lines && j >= 0 && j < cols)
p[i * cols + j] = value;
}
double &at(int i, int j)
{
if (i >= 0 && i < lines && j >= 0 && j < cols)
return p[i * cols + j];
};
double at(int i, int j) const
{
if (i >= 0 && i < lines && j >= 0 && j < cols)
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; i++)
{
for (int j = 0; j < cols; j++)
{
cout << p[i * cols + j];
if (j != cols - 1)
{
cout << ", ";
}
}
cout << "\n";
}
};
};
#endif
task5.cpp
#include <iostream>
#include "Matrix.hpp"
int main()
{
using namespace std;
double x[] = { 7, 6, 5, 4, 3, 2};
Matrix m1(3, 2); // 创建一个3×2的矩阵
m1.set(x); // 用一维数组x的值按行为矩阵m1赋值
m1.print(); // 打印矩阵m1的值
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,1, 123);
m3.print();
}