forked from demon90s/CppStudy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_13_58.cpp
79 lines (61 loc) · 1.32 KB
/
exercise_13_58.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
// 练习13.58:编写新版本的Foo类,其sorted函数中有打印语句,测试这个类,来
// 验证你对前两题的答案是否正确。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Foo {
public:
Foo &operator=(const Foo&) &; // 只能向可修改的左值赋值
Foo someMem() const &; // 正确,const限定符在前
Foo sorted() &&; // 可用于可改变的右值
Foo sorted() const &; // 可用于任何类型的Foo
private:
int a = 0;
vector<int> data;
};
Foo &Foo::operator=(const Foo &rhs) &
{
a = rhs.a;
return *this;
}
// 本对象为右值,因此可以原址排序
Foo Foo::sorted() &&
{
cout << "Foo Foo::sorted() &&" << endl;
sort(data.begin(), data.end());
return *this;
}
// 练习13.56,导致无限递归的版本
/*
Foo Foo::sorted() const &
{
cout << "Foo Foo::sorted() const &" << endl;
Foo ret(*this);
return ret.sorted();
}
*/
// 练习13.57,调用右值引用sorted的版本
Foo Foo::sorted() const &
{
cout << "Foo Foo::sorted() const &" << endl;
return Foo(*this).sorted();
}
// 返回一个引用;retFoo1调用是一个左值
Foo &retFoo1()
{
static Foo foo;
return foo;
}
// 返回一个值;retFoo2调用是一个右值
Foo retFoo2()
{
return Foo();
}
int main()
{
// tests
Foo foo;
foo.sorted();
return 0;
}