操作符重载05--流操作符(Stream Operators)
测试类.h
1: #pragma once
2: #include <iostream>
3: using namespace std;
4:
5: /*流操作符重载
6: 1. 流操作符为2元操作符,形式为 第一个参数 <<(>>) 第二个参数;
7: 2. 使用友元friend的形式,友元可以访问任何权限的成员变量,运算结果返回引用是
8: 为了可以写成这种形式os << pt1 << pt2,如果不返回则只能写成os << pt1;
9: */
10: class TRectangle
11: {
12: friend ostream& operator<<(ostream& Ostr, const TRectangle& Rect);
13: friend istream& operator>>(istream& Istr, TRectangle& Rect);
14: public:
15: TRectangle(double L = 0.00, double H = 0.00);
16: TRectangle(const TRectangle& R);
17: ~TRectangle();
18:
19: //method
20: void setLength(const double L) { Length = L; }
21: double getLength() const { return Length; }
22: void setHeight(const double H) { Height = H; }
23: double getHeight() const { return Height; }
24: double Perimeter() const { return 2 * (Length + Height); }
25: double Area() const { return Length * Height; }
26:
27: private:
28: double Length;
29: double Height;
30: };
31:
测试类.cpp
1: #include "StdAfx.h"
2: #include "TRectangle.h"
3:
4:
5: TRectangle::TRectangle(double L, double H) :
6: Length(L),
7: Height(H)
8: {
9: }
10:
11: TRectangle::TRectangle(const TRectangle& R) :
12: Length(R.Length),
13: Height(R.Height)
14: {
15: }
16:
17: TRectangle::~TRectangle(void)
18: {
19: }
20:
21: ostream& operator<<(ostream& Ostr, const TRectangle& R)
22: {
23: Ostr << "长为:" << R.Length << "宽为:" << R.Height << endl;
24: return Ostr;
25: }
26:
27: istream& operator>>(istream& Istr, TRectangle& R)
28: {
29: cout << "长: ";
30: Istr >> R.Length;
31: cout << "宽: ";
32: Istr >> R.Height;
33: return Istr;
34: }
main
1: // StreamOperators.cpp : 定义控制台应用程序的入口点。
2: //
3:
4: #include "stdafx.h"
5: #include "TRectangle.h"
6:
7:
8: int _tmain(int argc, _TCHAR* argv[])
9: {
10: TRectangle Ra(10.5, 5.66), Rb(1, 2), Rc;
11: cout << Ra << Rb;
12: cin >> Rc;
13: cout << Rc;
14: return 0;
15: }
16:
测试结果图