关于运算符重载的问题 [英] a question about operator overloading

查看:122
本文介绍了关于运算符重载的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我故意写下面的代码并且它有效!

I intentionally wrote the following code and it worked!

#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;

class MaTrix
{
	private:
		int v[10][10],n,m;
	public: 
		friend void operator>>(istream& is, MaTrix &m);
		friend void operator<<(ostream& os, MaTrix m);
		void find_max();
};

//-------------------------------

void operator>>(istream& is, MaTrix &m)
{
	cout<<"Input rows = ";is>>m.n;
	cout<<"Input columns = ";is>>m.m;
	for(int i=0;i<m.n;i++)
		for(int j=0;j<m.m;j++)
		{
			cout<<"Input value v["<<i<<"]["<<j<<"]=";is>>m.v[i][j];
		}
	cout<<"Finish!"<<endl;
}

void operator<<(ostream& os,MaTrix m)
{
	int j;
	for(int i=0;i<m.n;i++)
	{
		for(j=0;j<m.m;j++)
			os<<setw(6)<<m.v[i][j];
		if(j==m.m) os<<endl;
	}
}

void MaTrix::find_max()
{
	int max=v[0][0];
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
			if(v[i][j]>max) max=v[i][j];
	cout<<"Max = "<<max<<endl;
	system("pause");
}

int main()
{
	MaTrix mt;
	cout<<"Input a matrix"<<endl;cin>>mt;
	cout<<"The matrix is : "<<endl;
	cout<<mt;
	mt.find_max();
	return 0;
}





在我的课程中,代码为:



In my lesson the code is :

istream& operator>>(istream& is, MaTrix &m)
{
	cout<<"Input rows = ";is>>m.n;
	cout<<"Input columns = ";is>>m.m;
	for(int i=0;i<m.n;i++)
		for(int j=0;j<m.m;j++)
		{
			cout<<"Input value v["<<i<<"]["<<j<<"]=";is>>m.v[i][j];
		}
	cout<<"Finish!"<<endl;
        return is;
}

ostream& operator<<(ostream& os,MaTrix m)
{
	int j;
	for(int i=0;i<m.n;i++)
	{
		for(j=0;j<m.m;j++)
			os<<setw(6)<<m.v[i][j];
		if(j==m.m) os<<endl;
	}
        return os;
}





你能告诉我他们有什么不同吗?如果我使用第一个代码会出现什么问题?



Could you tell me how they different? And what is problem if I use the first code?

推荐答案

如果你考虑它就很简单。区别在于返回参数,在C ++中,人们喜欢编写如下代码:



Its simple if you think about it. The difference is the return parameters, in C++, people like to write code like:

cout << myvariable << mytext << endl;





只有<<成员上的重载返回一个ostream对象。如果返回void,则在编写上述行时将出现编译错误。您返回ostream对象,以便链接<< operator。



Which is only possible if the << overloads on the members return an ostream object. If you return void, you will get a compilation error when you write the above line. You return the ostream object so that you can chain << operators.


think bit cin>>和cout<<多数民众赞成它属于#include< iostream.h>相同的概念。但如果它是无效的,那么它们就没有任何返回类型.reason is void意味着没有任何返回类型。
think bit cin>> and cout<< thats it is belong to #include<iostream.h> same concept.but if it is void then their is no any return type.reason is void mean no any return type.


这篇关于关于运算符重载的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆