uacs2024

导航

C++ 输入/输出运算符重载

C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。您可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。

在这里,有一点很重要,我们需要把运算符重载函数声明为类的友元函数,这样我们就能不用创建对象而直接调用函数。

下面的实例演示了如何重载提取运算符 >> 和插入运算符 <<

 1 #include <iostream>
 2 using namespace std;
 3  
 4 class Distance
 5 {
 6    private:
 7       int feet;             // 0 到无穷
 8       int inches;           // 0 到 12
 9    public:
10       // 所需的构造函数
11       Distance(){
12          feet = 0;
13          inches = 0;
14       }
15       Distance(int f, int i){
16          feet = f;
17          inches = i;
18       }
19       friend ostream &operator<<( ostream &output, const Distance &D )
21       { 
22          output << "F : " << D.feet << " I : " << D.inches;
23          return output;            
24       }
25  
26       friend istream &operator>>( istream  &input, Distance &D )
27       { 
28          input >> D.feet >> D.inches;
29          return input;            
30       }
31 };
32 int main()
33 {
34    Distance D1(11, 10), D2(5, 11), D3; 
35    cout << "Enter the value of object : " << endl;
36    cin >> D3;
37    cout << "First Distance : " << D1 << endl;
38    cout << "Second Distance :" << D2 << endl;
39    cout << "Third Distance :" << D3 << endl;
40    return 0;
41 }

结果

$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10

 

posted on 2024-03-02 21:28  ᶜʸᵃⁿ  阅读(7)  评论(0编辑  收藏  举报