相关知识:
- C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。您可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。
- 在这里,有一点很重要,我们需要把运算符重载函数声明为类的友元函数,这样我们就能不用创建对象而直接调用函数。
代码涉及内容:
操作符重载
输出操作符 << 重载
- 非成员函数 要写为 友元函数
- 少做格式化
输入操作符 >> 重载 - 处理输入操作的错误(输出一般不会错误)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using namespace std;
class Dog
{
};
class Sales_item
{
// 需要将重构操作符的函数设为友元函数,这样才能访问类的私有成员;
friend ostream& operator<<(ostream& out, const Sales_item& s);
friend istream& operator>>(istream& in, Sales_item& s);
public:
Sales_item(string book, unsigned units, double price):
isbn(book),units_sold(units),revenue(units * price){}
Sales_item():units_sold(0),revenue(0.0){}
private:
string isbn;
unsigned units_sold;
double revenue;
};
// 返回类型必须为 ostream&,且第一个参数类型为ostream&;
ostream& operator<<(ostream& out, const Sales_item& s)
{
out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue;
return out;
}
// 输出操作符设为const,输入不再设为const,因为输入要进行改变;
istream& operator>>(istream& in, Sales_item& s)
{
double price;
in >> s.isbn >> s.units_sold >> price;
// 检查输入错误
if (in)
s.revenue = s.units_sold * price;
else // 如果输入错误,返回为空字符串,0,0.0
s = Sales_item();
s.revenue = s.units_sold * price;
return in;
}
int main()
{
Dog a;
int b = 0;
cout << "hello HTL2018" << endl;
Sales_item item(string("0-201-78354-X"),2,25.00);
// 此时就可以进行输出,因为上面已经定义了输出操作符的重构函数;
cout << item << endl;
cin >> item;
cout << item << endl;
//cout << a << endl; // 此处不能直接输出 a ,因为没有定义a的输出操作符的重载,程序不知道如何输出;
cout << b << endl;
return 0;
}代码执行结果:
参考链接:
C++ 输入/输出运算符重载