C++ 输入/输出运算符重载
C++ 使用 流提取运算符 >>
和流插入运算符 <<
来输入和输出内置的数据类型
C++ 允许重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型
可以把运算符重载函数声明为类的友元函数,如此就能不用创建对象而直接调用函数
/** * file: main.cpp * author: 简单教程(www.twle.cn) * * Copyright © 2015-2065 www.twle.cn. All rights reserved. */ #include <iostream> class Rect { public: double width; double height; Rect() { width = 0; height = 0; } Rect(double a, double b ) { width = a; height = b; } double area() { return width * height; } friend std::ostream &operator<<( std::ostream &output, Rect &r) { output << "width : " << r.width; output << " height : " << r.height; output << " area: " << r.area(); return output; } friend std::istream &operator>>( std::istream &input, Rect &r ) { input >> r.width >> r.height; return input; } }; int main() { Rect r1(3.0, 4.0), r2(6.0, 8.0), r3; std::cout << "Enter the value of object : \n"; std::cin >> r3; std::cout << "r1: " << r1 << std::endl; std::cout << "r2: " << r2 << std::endl; std::cout << "r3: " << r3 << std::endl; return 0; }
编译和运行以上范例,输出结果如下:
Enter the value of object : 12.0 13.0 r1: width : 3 height : 4 area: 12 r2: width : 6 height : 8 area: 48 r3: width : 12 height : 13 area: 156