前言
首先晒一个标准输入输出格式的表格,这些算是命令还是标志位还是操作符呢?
C++输入输出标准库提供了“>>”和“<<”运算符执行输入、输出操作,但标准库只定义了基本数据类型的输入、输出操作,若要直接对类对象进行输入、输出,则需要在类中重载这两个运算符。与其他运算符不同的是,输入、输出运算符只能重载成类的友元函数。“<<”和“>>”运算符重载的格式如下:
ostream& operator<<(ostream&, const 类对象引用); //输出运算符重载
istream& operator>>(istream&, 类对象引用); //输入运算符重载
输出运算符“<<”重载的第一个参数是ostream对象引用,该对象引用不能使用const修饰,第二个参数是输出对象的const引用。输入运算符“>>”重载的第一个参数是istream对象引用,第二个参数是要向其中存入数据的对象,该对象不能使用const修饰。
下面通过案例演示输入/输出运算符重载的用法:
#include <iostream>
#include <iomanip>
using namespace std;
class myclass{
friend ostream& operator<<(ostream &o,const myclass &c);
friend istream& operator>>(istream &i,myclass &c);
public:
myclass(int n):num(n){
cout << "class init" << endl;
}
~myclass(){
cout << "class destroy" << endl;
}
void show(){
cout << "num = " << num << endl;
}
private:
int num;
};
ostream& operator<<(ostream &o,const myclass &c){
o << c.num;
return o;
}
istream& operator>>(istream &i,myclass &c){
i >> c.num;
return i;
}
int main()
{
myclass c(10);
cout << c << endl;
cin >> c;
c.show();
return 0;
}
执行结果:调用了cin,所以测试时输入一个数字,如下所示,输入20,调用show函数后输出20.
class init
10
20
num = 20
class destroy