函数对象:使用方式看上去像函数,但实际是类的一个对象;是因为类重载了“()”运算符,所以让对象使用的方式看起来是函数,即对象后面的括号像函数一样调用。

1
2
3
4
5
struct Adder {               // 1. 类重载了 operator()
int operator()(int a, int b) const { return a + b; }
};
Adder add; // 2. 函数对象
int r = add(3, 4); // 调用函数对象

友元函数不是类的成员函数,但它可以访问类的私有和保护成员,为操作符重载提供了灵活性。

1
2
3
friend std::ostream& operator<<(std::ostream& os, const Student& s) {
return os << '[' << s.id << ',' << s.score << ',' << s.name << ']';
}

如果不用 friend 而作为成员函数,只能是 this 对象的操作符,即 Student::operator<<(std::ostream&),这样调用方式会变成 student << cout,不符合常规用法,需要保持 cout << object 这种自然的语法结构。