matrix 重载操作,firend 函数实现 简单的例子

#include<iostream>
#define MAX 10
using namespace std;
class matrix;
matrix& operator-(matrix& b,const matrix& c);
class matrix
{
private:
	int row,col,(*a)[MAX];
public:
	matrix(){}
	matrix(int r,int c,int (*b)[MAX]):row(r),col(c),a(b){}
	matrix& operator+(const matrix& b)
	{
		for(int i=0;i<row;i++)
			for(int j=0;j<col;j++)
				a[i][j]=a[i][j]+b.a[i][j];
		return *this;
	}
	friend matrix& operator-(matrix& b,const matrix& c)
	{
       	for(int i=0;i<b.row;i++)
			for(int j=0;j<b.col;j++)
             b.a[i][j]=b.a[i][j]-c.a[i][j];
		return b;
	}
    void show()
	{ 
      	for(int i=0;i<row;i++)
		{
			for(int j=0;j<col;j++)
				cout<<a[i][j]<<" ";
			cout<<endl;
		}
	}
};

void main()
{
	int row =2 ,col =3,a[2][MAX]={{1,2,3},{4,5,6}};
	matrix mat1(row,col,a);
	int b[2][MAX]={{4,3,2},{1,2,3}};
	matrix mat2(row,col,b);
	matrix mat3;
	mat3 = mat1 + mat2;
	cout<<"mat3"<<endl;
	mat3.show();
	cout<<"mat1"<<endl;
	mat1.show();
	cout<<"mat4"<<endl;
	matrix mat4;
	mat4 = mat1 - mat2;
	mat4.show();
}




重载例子:

#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
#define N  20
class CBook
{
private:
	char name[N];
	double price;
public:
	CBook(char* n,double p){strcpy(name,n);price=p;}
	CBook(const CBook&c)
	{
		strcpy(name,c.name);
		price = c.price;
	}
	CBook&operator=(const CBook s)
	{
		strcpy(name,s.name);
		price = s.price;
		return *this;
	}
	char& operator[](int i)
	{
		if(i>=0)
			return name[i];
		return name[N-1];
	}
	bool operator>(const CBook c)
	{
		return price>c.price;
	}
	friend istream& operator>>(istream& in,CBook& c)
	{
		in>>c.price;
		return in;
	}
	friend ostream& operator<<(ostream& out,CBook c)
	{
		out<<c.name<<" "<<c.price<<endl;
		return out;
	}
    ~CBook()
	{

	}
}; 
void main()
 {
 CBook hlm("红楼梦", 34.5), sgyy("三国演义", 45.6), xinshu = sgyy;

     cin >> hlm >> sgyy;
     cout << hlm << sgyy;
     if (hlm > sgyy)
        cout << "红楼梦比三国演义贵\n";
     else
        cout << "红楼梦比三国演义便宜\n";

     cout << xinshu;
     xinshu[-2] = '1';
     xinshu[10] = '1';
     xinshu[0] = '1';
     cout << xinshu;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值