为什么这么写ostream& operator << (ostream& os, Point&...

本文详细解释了C++中ostream操作符<<的重载方式,对比了两种不同的实现方法,阐述了为何需要返回ostream引用的原因,以及如何使得连续输出操作成为可能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么这么写ostream& operator << (ostream& os, Point& pt)
而不写成ostream operator << (ostream& os, Point& pt)
ostream这个返回值类型用定义成别名的形式吗??

------------------------------------------------------------ 
如果写成这样
ostream operator << (ostream& os, Point& pt) 
则:
Point a, b;
cout<<a<<b;
错误,只能写为:
cout<<a;
cout<<b;
原因在于
cout<<a<<b;
相当于:
(cout<<a)<<b;
第一个()中返回cout的临时变量,它可以不可以作为左值。因而错误。

如果写成:
ostream& operator << (ostream& os, Point& pt) 
则:
cout<<a<<b;
正确,因为它等同于
(cout<<a)<<b;
(acout<<a)返回cout的引用,即就是它自己,它可以再次作为左值。因而能够连着写这个输出流

转载于:https://my.oschina.net/ypimgt/blog/129877

#include <iostream&gt;using namespace std;const double PI = 3.14159265358979323846;class Point {public: Point(double xx = 0, double yy = 0) : x(xx), y(yy) {} friend istream& operator>>(istream& is, Point&amp; p); friend ostream&amp; operator<<(ostream&amp; os, const Point&amp; p);protected: double x, y;};istream& operator>>(istream& is, Point&amp; p) { is >> p.x >> p.y; return is;}ostream&amp; operator<<(ostream&amp; os, const Point&amp; p) { os << "(" << p.x << ", " << p.y << ")"; return os;}class Circle : public Point {public: Circle(double xx = 0, double yy = 0, double rr = 0) : Point(xx, yy), r(rr) {} double area() const { return PI * r * r; } friend istream& operator>>(istream& is, Circle& c); friend ostream&amp; operator<<(ostream&amp; os, const Circle& c);protected: double r;};istream& operator>>(istream& is, Circle& c) { is >> static_cast<Point&amp;>(c) >> c.r; return is;}ostream&amp; operator<<(ostream&amp; os, const Circle& c) { os << "Center: " << static_cast<const Point&amp;>(c) << ", Radius: " << c.r; return os;}class Cylinder : public Circle {public: Cylinder(double xx = 0, double yy = 0, double rr = 0, double hh = 0) : Circle(xx, yy, rr), h(hh) {} double volume() const { return Circle::area() * h; } friend istream& operator>>(istream& is, Cylinder& cy); friend ostream&amp; operator<<(ostream&amp; os, const Cylinder& cy);protected: double h;};istream& operator>>(istream& is, Cylinder& cy) { is >> static_cast<Circle&>(cy) >> cy.h; return is;}ostream&amp; operator<<(ostream&amp; os, const Cylinder& cy) { os << "Base: " << static_cast<const Circle&>(cy) << ", Height: " << cy.h; return os;}int main() { Circle c(0, 0, 1); cout << "Input circle info: "; cin >> c; cout << c << endl; cout << "Circle area: " << c.area() << endl; Cylinder cy(0, 0, 1, 2); cout << "Input cylinder info: "; cin >> cy; cout << cy << endl; cout << "Cylinder volume: " << cy.volume() << endl; return 0;}输出结果是
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值