Overloading the << Operator for Your Own Classes
来源:互联网 发布:unity3d fbx模型 编辑:程序博客网 时间:2024/06/10 11:35
Output streams use the insertion (<<) operator for standard types. You can also overload the << operator for your own classes.
Example
The write function example showed the use of a Date structure. A date is an ideal candidate for a C++ class in which the data members (month, day, and year) are hidden from view. An output stream is the logical destination for displaying such a structure. This code displays a date using the cout object:
Date dt( 1, 2, 92 );cout << dt;
To get cout to accept a Date object after the insertion operator, overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so it can access the private data within a Date object.
// overload_date.cpp// compile with: /EHsc#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& os, const Date& dt);};ostream& operator<<(ostream& os, const Date& dt){ os << dt.mo << '/' << dt.da << '/' << dt.yr; return os;}int main(){ Date dt(5, 6, 92); cout << dt;}
5/6/92
Remarks
The overloaded operator returns a reference to the original ostream object, which means you can combine insertions:
cout << "The date is" << dt << flush;
See Also
Reference
- Overloading the << Operator for Your Own Classes
- Operator Overloading
- Operator overloading
- Operator Overloading
- The String class is provided in the Java library. Provide your own implementation for the following
- Taking Responsibility for Your Own Learning
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Android.mk for your own module
- Create your own .pfx file for ClickOnce
- Android.mk for your own module
- build your own kernel Image for Nexus10
- List vs Array:谁适合做java中泛型对象的容器?
- 黑马程序员_细说接口
- [LeetCode38]Count and Say
- windows sdk编程系列文章 ---- 利用镂空制作特效界面
- Java 常用类
- Overloading the << Operator for Your Own Classes
- 状态压缩动态规划 -- 旅行商问题
- 李克强:有信心实现今年经济增长7.5%目标
- JavaWeb:报错信息The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- 友元函数(friend)
- [LeetCode39]Combination Sum
- 使用 Jackson 库生成解析 json
- install pydev in eclipse
- 2014E3游戏展回顾 大作频发精彩不断