<C++类与对象>new 操作符、构造函数、拷贝构造函数、析构函数、重载运算符

这篇博客介绍了如何使用C++进行面向对象编程,具体展示了如何设计和实现一个名为Matrix的矩阵类。该类包含了构造函数、拷贝构造函数和析构函数,实现了矩阵加法和乘法的重载运算符,以及输入输出的重载运算符。通过示例代码,博主展示了如何创建、初始化、操作和打印矩阵,并提供了主函数作为测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++面向对象程序设计课程的作业,初学者,很多地方做的不好,欢迎指正。

题目要求:

定义矩阵类 Matrix,包含整数型私有成员变量 row 和 col,分别代表矩阵的行数和列数。矩阵元素存储于通过 new 操作符获取的一维数组,定义该类的构造函数拷贝构造函数析构函数(delete申请的堆资源)重载算术运算符+和*,使之实现矩阵加法和乘法运算;重载<<和>>运算符,使之能用于该矩阵的输入和输出。

#include<iostream>
using namespace std;

class Matrix
{
    public:
        Matrix() {}//构造函数
        Matrix(int r,int c,int a[])//构造函数
            {row=r;col=c;arr=a;}
        Matrix(const Matrix &A)//拷贝构造函数
            {row=A.row;col=A.col;arr=A.arr;}
        ~Matrix()//析构函数
            {delete []arr;}//delete申请的堆资源
        Matrix operator+(Matrix &A);//重载算术运算符+
        Matrix operator*(Matrix &A);//重载算术运算符*
        friend ostream & operator<<(ostream &,const Matrix &);//重载输出运算符<<
        friend istream & operator>>(istream &,Matrix &);//重载输入运算符>>
    private:
        int row,col;//行数、列数
        int *arr=new int[100];//矩阵元素
};

Matrix Matrix::operator+(Matrix &A)//重载算术运算符+,实现矩阵加法
{
    int i,j;
    Matrix res;
    res.row=row;
    res.col=col;
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            res.arr[i*col+j]=arr[i*col+j]+A.arr[i*col+j];
        }
    }
    return res;
}

Matrix Matrix::operator*(Matrix &A)//重载算术运算符*,实现矩阵乘法
{
    int i,j,k,result=0;
    Matrix res;
    res.row=row;
    res.col=A.col;
    for(i=0;i<row;i++)
    {
        for(j=0;j<A.col;j++)
        {
            for(k=0;k<col;k++)
            {
                result+=arr[i*col+k]*A.arr[k*A.col+j];
            }
            res.arr[i*col+j]=result;
            result=0;
        }
    }
    return res;
}

ostream & operator<<(ostream & out,const Matrix &A)//重载运算符<<,实现矩阵输出
{
    int i,j;
    out<<A.row<<" ";
    out<<A.col;
    out<<endl;
    for(i=0;i<A.row;i++)
    {
        for(j=0;j<A.col;j++)
        {
            out<<A.arr[i*A.col+j]<<" ";
        }
        out<<endl;
    }
    return out;
}

istream & operator>>(istream & in,Matrix &A)//重载运算符>>,实现矩阵输入
{
    in>>A.row;
    in>>A.col;
    int i,j;
    for(i=0;i<A.row;i++)
    {
        for(j=0;j<A.col;j++)
        {
            in>>A.arr[i*A.col+j];
        }
    }
    return in;
}

int main()
{
    //输出矩阵按照此格式:第一行两个数为行数、列数,第二行及以后为矩阵元素
    Matrix x,y,sum,product;
    cout<<"the pattern: \nrow col\nelements\n\nx:\n";
    cin>>x;
    cout<<"y:\n";
    cin>>y;

    sum=x+y;
    product=x*y;
    cout<<"x and y sum is "<<endl;
    cout<<sum<<endl;
    cout<<"x and y product is "<<endl;
    cout<<product<<endl;

    //delete申请的堆资源
    x.~Matrix();
    y.~Matrix();
    sum.~Matrix();
    product.~Matrix();
    return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值