function call ()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class LessThan {
public:
bool operator()(const int& num) {
return num < 5;
}
};

int main() {
vector<int> nums{1, 2, 7, 4, 6, 3};
auto mycmp = [](const int& a) {return a < 6;};

auto it1 = find_if(nums.begin(), nums.end(), mycmp);
auto it2 = find_if(nums.begin(), nums.end(), LessThan());

cout << *it1 << endl;
cout << *it2 << endl;

return 0;
}

iostream运算符(<<、>>)

类内实现需要使用友元函数,类外实现不能使用const

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
// 友元方式实现
class A {
public:
A(int a = 0, int b = 0) : _a(a), _b(b) {}
int geta() {return _a;}
int getb() {return _b;}

friend ostream& operator<<(ostream& os, const A& t) {
os << "a = " << t._a << ", b = " << t._b;
return os;
}

friend istream& operator>>(istream& os, A& t) {
os >> t._a >> t._b;
return os;
}

private:
int _a, _b;
};


// 类外函数方式
class A {
public:
A(int a = 0, int b = 0) : _a(a), _b(b) {}
int geta() {return _a;}
int getb() {return _b;}

private:
int _a, _b;
};

ostream& operator<<(ostream& os, A& t) {
os << "a = " << t.geta() << ", b = " << t.getb();
return os;
}