⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 输入输出的操作符重载.txt

📁 里面的代码是自己写的,参考书是thingking in c++,代码有详细的说明,对学习c++语法非常有帮助!
💻 TXT
字号:
/*本程序选自P518
* 本程序主要是为了说明输入输出操作符的重载方法
*/

#include <iostream>
#include <string>
#include <cassert>
using namespace std;

class IntArray
{
	static const int sz = 10;
	int i[sz];
public:
	IntArray();
	int & operator[] ( int x ) {
		assert( x>=0 && x < sz );
		return i[x];
	}
	friend ostream & operator<< ( ostream & os, const IntArray & ia );

	friend istream & operator>> ( istream & is, IntArray & ia);
};

const int IntArray::sz;
IntArray::IntArray() 
{
	int index;
	for( index = 0; index < sz; ++index)
		i[index]= index;
	cout << " constructor called "<< endl;
}

ostream & operator<< ( ostream &os,const IntArray & ia )
{
	for (int j=0;j < ia.sz; j++)
	{
		os << ia.i[j];
		if ( j != ia.sz-1)
			os <<", ";
	}
	os << endl;
	return os;
}

 //在第二个形参IntArray & ia前面加了个const则错误很奇怪:error C2248: “IntArray::sz” : 无法访问 private 成员(在“IntArray”类中声明)
//error C2248: “IntArray::i” : 无法访问 private 成员(在“IntArray”类中声明)
// error C2679: 二进制“>>” : 没有找到接受“<未知>”类型的右操作数的运算符(或没有可接受的转换)

istream & operator>> ( istream &is, IntArray & ia )
{
	for (int j = 0; j < ia.sz; j++)
		is >> ia.i[j];
	return is;
}



int main()
{
	IntArray I;
    cin >> I;
	cout << "输出"<< endl;
	cout << I;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -