重载输入输出 与操作符重载相同
要主义的是 cout 与cin 的类型是什么
cout 与 cin 都是iostream 里的类对象
cout的类型是 ostream
cin的类型是istream
我们想通过cout直接输出类里的成员变量
cout<<num<<endl;
可通过操作符重载来实现
ostream& operator <<(ostream& os, Num& num)
{
os << num.nValue << endl;
return os;
}
istream& operator >>(istream& is, Num& num)
{
is >> num.nValue;
return is;
}
完整代码如下:
#include<iostream>
using namespace std;
class Num
{
public :
int nValue;
public:
Num(int n)
{
nValue = n;
}
public:
};
ostream& operator <<(ostream& os, Num& num)
{
os << num.nValue << endl;
return os;
}
istream& operator >>(istream& is, Num& num)
{
is >> num.nValue;
return is;
}
int main()
{
Num num(100);
cout << num << endl;
cin >> num;
cout << num << endl;
return 0;
}
//++的重载为特殊情况 带参数得是右++ 不带参数得是左++
其中 重载++符号是一个特例
一般的 在类中我们对++符号的重载分为左++和右++
根据++运算符的定义
左++返回的是++之后的值
右++返回的是++之前的值
所以 我们对右++重载时 传一个参数n来记录我们++之前得值用来返回
右++:
public:
int operator ++(int n)//右++
{
n = nValue;
nValue = nValue + 1;
return n;
}
左++
int operator ++()//左++
{
nValue = nValue + 1;
return nValue;
}
完整代码如下
#include<iostream>
using namespace std;
class Num
{
private:
int nValue;
public:
Num(int n)
{
nValue = n;
}
public:
int operator ++(int n)//右++
{
n = nValue;
nValue = nValue + 1;
return n;
}
int operator ++()//左++
{
nValue = nValue + 1;
return nValue;
}
};
int main()
{
Num num(100);
cout << num++ << endl;
cout << ++num << endl;
return 0;
}
//++的重载为特殊情况 带参数得是右++ 不带参数得是左++