C++重载运算符“<<”,for your class/struct
2016-08-04 19:56
344 查看
需求
你写了一个日期类,然后想通过一个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; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android Native 绘图方法
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#中struct和class的区别详解
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- VBS ArrayList Class vbs中的数组类
- 大家看了就明白了css样式中类class与标识id选择符的区别小结
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结