顺便学习使用“<<”与“>>”的重载
#include<iostream>
using namespace std;
class C
{
//重载“<<”与“>>”,作为全局函数,作为类的友元,访问类的私有成员变量
friend ostream & operator <<(ostream&out, C&c);
friend istream & operator >>(istream&in, C&c);
private:
int b;
public:
C(int b)
{
this->b = b;
}
C& operator ++()//代表前缀自加
{
this->b += 1;
return *this;
}
const C operator++(int)//代表后缀自加,int纯粹只是为了区分前后缀
{
int oldb = this->b;
++(*this);//使用前缀自加,统一自加行为
return C(oldb);
}
C(const C & c)
{
this->b = c.b;
}
void print()
{
cout << b << endl;
}
};
ostream &operator <<(ostream&out, C&c)
{
out << c.b;
return out;
}
istream &operator >>(istream&in, C&c)
{
cout << "请输入b值:";
in >> c.b;
if (!in)
c.b = 0;
return in;
}
int main()
{
C c1(2);
cout << "c1:" << c1 << endl;
cin >> c1;
cout << "c1:" << c1 << endl;
C c2(c1);
cout << "c2:" << c2 << endl;
C c3 = c1++;
//C c4 = c1++++;//后面的++想修改c1++返回的const对象,所以报错
cout << "c1:" << c1 << endl;
cout << "c3:" << c3 << endl;
C c5 = ++c1;
cout << "c1:" << c1 << endl;
cout << "c5:" << c5 << endl;
C c6 = ++++c1;
cout << "c1:" << c1 << endl;
cout << "c6:" << c6 << endl;
system("pause");
return 0;
}