实验四

task5

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdlib.h>
#include<iostream>
#include<iomanip>

using std::cout;
using std::endl;
using std::setw;
using std::left;

class vectorInt
{ 
     public:
         vectorInt(int num);
         vectorInt(int num, int value);
         vectorInt(const vectorInt& obj);
         ~vectorInt();

         int& at(int i) { return n[i];}
         int get_size() { return size; }
         friend void output(vectorInt&obj);

     private:
         int* n,size;

};

vectorInt::vectorInt(int num) :size{num}
{
    cout << "constuctot 1 called" << endl;
    n = (int*)malloc(sizeof(int) * num);
}
vectorInt::vectorInt(int num, int value) :size{num}
{
    cout << "constuctot 2 called" << endl;
    n= (int*)malloc(sizeof(int) * num);
    for (int i = 0; i < num; ++i)
        n[i] = value;
}
vectorInt::vectorInt(const vectorInt& obj) :size{obj.size}
{
    cout << "copy constuctot called" << endl;
    n = (int*)malloc(sizeof(int) * obj.size);
    for (int i = 0; i < obj.size; ++i)
        n[i] = obj.n[i];
}
vectorInt::~vectorInt()
{
    free(n);
    cout << "destructor called" << endl;
}

void output(vectorInt&obj)
{
    for (int i = 0; i < obj.size; ++i)
        cout << setw(3) << left << obj.n[i];
    cout << endl;
}

  实验结果

 

 task6

#pragma once
#include <iostream>
#include<stdlib.h>
#include<iomanip>

using std::cout;
using std::endl;
using std::setw;
using std::left;

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) { p[i][j] = value; }
		double& at(int i, int j) { return p[i][j]; }
		double at(int i, int j) const { return p[i][j]; }
		int get_lines() const { return lines; }
		int get_cols() const { return cols; }
		void print() const;

	private:
		int lines, cols;
		double **p;
};

Matrix::Matrix(int n) :lines{ n }, cols{n}
{
	p = (double**)malloc(sizeof(double) * n);
	for (int i = 0; i < n; ++i)
		p[i] = (double*)malloc(sizeof(double) * n);
}
Matrix::Matrix(int n, int m) :lines{ n},cols{ m }
{
	p = (double**)malloc(sizeof(double) * n);
	for (int i = 0; i < n; ++i)
		p[i] = (double*)malloc(sizeof(double) * m);
}
Matrix::Matrix(const Matrix& X) :lines{ X.lines }, cols{ X.cols } 
{
	p = (double**)malloc(sizeof(double) * X.lines);
	for (int i = 0; i < X.lines; ++i)
		p[i] = (double*)malloc(sizeof(double) * X.cols);
	for (int i = 0; i < X.lines; ++i)
		for (int j = 0; j < X.cols; ++j)
			p[i][j] = X.at(i,j);
}
Matrix::~Matrix()
{
	for(int i=0;i<lines;++i)
		free(p[i]);
	free(p);
}

void Matrix::set(const double* pvalue)
{
	for (int i = 0; i < lines; ++i)
		for (int j = 0; j < cols; ++j)
			p[i][j] = pvalue[i * cols + j];
}
void Matrix::print() const
{
	for (int i = 0; i < lines; ++i)
	{
		for (int j = 0; j < cols; ++j)
			cout <<setw(4)<<left<< int(p[i][j]);
		cout << endl;
	}
}

  实验结果

 

posted @ 2022-11-01 20:37  gosj  阅读(53)  评论(0)    收藏  举报