需求
你写了一个日期类,然后想通过一个cout
直接按照格式输出日期:
Date dt(11, 11, 2011);
cout << dt << endl;
为了让cout
能够接受一个Date
对象,这就需要为Date类
重载<<
运算符。
举例
// overload_date.cpp
#include <iostream>
using namespace std;
class Date {
int mo, da, yr;
public:
Date(int m, int d, int y) {
mo = m;
da = d;
yr = y;
}
friend ostream& operator <<(ostream &co, const Date &dt);
};
ostream& operator <<(ostream &co, const Date &dt) {
co << "mm:dd:yy = " << dt.mo << ":" << dt.da << ":" << dt.yr;
return co;
}
int main(void) {
Date d(11, 11, 2011);
cout << d << endl; //mm:dd:yy = 11:11:2011
return 0;
}
关于友元函数(friend)
虽然友元函数定义在类中,但是,友元函数不属于类。同时,虽然不属于累,但是,它可以操作类中的private和protected成员。
结构体struct VS 类class
其实,叫类struct就是了。
最主要基本上也是唯一的区别:
默认的访问权限不同
类可以在它的第一个访问说明符之前定义成员,对这种成员的访问权限依赖于类定义的方式。如果使用struct关键字,则定义在第一个访问说明符之前的成员是public;相反,如果使用class关键字,则这些成员是private的。
举例
#include <iostream>
using namespace std;
struct Point { //是不是跟类一样
int x, y;
Point(int x=0, int y=0):x(x), y(y) {} //构造函数
};
Point operator + (const Point &A, const Point &B) {
return Point(A.x+B.x, A.y+B.y);
}
ostream &operator << (ostream &out, const Point &p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
int main(void) {
Point a, b(1, 2);
a.x = 3;
//直接可以加,是不是爽歪歪了...
cout << a+b << endl; //(4, 2)
//cout.setf(ios::left|ios::showpoint);
//cout << 123.45678 << endl;
//cout << hex << 12 << endl;
return 0;
}