七、函数对象
7.1 函数对象基础
cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
// 函数对象(仿函数):重载operator()的类
// 1. 简单函数对象
class Adder {
private:
int value;
public:
Adder(int v) : value(v) {}
int operator()(int x) const {
return x + value;
}
};
// 2. 带状态的函数对象
class Counter {
private:
int count;
public:
Counter() : count(0) {}
int operator()() {
return ++count;
}
void reset() { count = 0; }
};
// 3. 谓词函数对象
class IsEven {
public:
bool operator()(int n) const {
return n % 2 == 0;
}
};
// 4. 比较函数对象
class CompareByLength {
public:
bool operator()(const string& a, const string& b) const {
return a.length() < b.length();
}
};
int main() {
// 使用函数对象
Adder add5(5);
cout << "add5(10) = " << add5(10) << endl;
Counter counter;
for (int i = 0; i < 5; i++) {
cout << counter() << " ";
}
cout << endl;
// 与STL算法配合
vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 使用函数对象作为谓词
auto it = find_if(numbers.begin(), numbers.end(), IsEven());
cout << "第一个偶数: " << *it << endl;
// 转换
vector<int> results;
transform(numbers.begin(), numbers.end(), back_inserter(results), Adder(10));
// 排序
vector<string> words = {"apple", "banana", "pear", "grapefruit", "kiwi"};
sort(words.begin(), words.end(), CompareByLength());
for (const auto& w : words) {
cout << w << " ";
}
cout << endl;
return 0;
}
7.2 标准函数对象
cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
// 算术运算
plus<int> add;
minus<int> sub;
multiplies<int> mul;
divides<int> div;
cout << "add(10, 20) = " << add(10, 20) << endl;
cout << "sub(10, 20) = " << sub(10, 20) << endl;
cout << "mul(10, 20) = " << mul(10, 20) << endl;
cout << "div(20, 10) = " << div(20, 10) << endl;
// 比较运算
greater<int> gt;
less<int> lt;
equal_to<int> eq;
cout << "gt(10, 20) = " << gt(10, 20) << endl;
cout << "lt(10, 20) = " << lt(10, 20) << endl;
cout << "eq(10, 10) = " << eq(10, 10) << endl;
// 逻辑运算
logical_and<bool> land;
logical_or<bool> lor;
logical_not<bool> lnot;
cout << "land(true, false) = " << land(true, false) << endl;
cout << "lor(true, false) = " << lor(true, false) << endl;
cout << "lnot(true) = " << lnot(true) << endl;
// 使用标准函数对象与算法
vector<int> data = {5, 2, 8, 1, 9, 3};
// 升序排序
sort(data.begin(), data.end(), less<int>());
cout << "升序: ";
for (int n : data) cout << n << " ";
cout << endl;
// 降序排序
sort(data.begin(), data.end(), greater<int>());
cout << "降序: ";
for (int n : data) cout << n << " ";
cout << endl;
// 累加
int sum = accumulate(data.begin(), data.end(), 0, plus<int>());
cout << "总和: " << sum << endl;
return 0;
}
7.3 std::function
cpp
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
// 普通函数
int add(int a, int b) {
return a + b;
}
// 函数对象
class Multiplier {
private:
int factor;
public:
Multiplier(int f) : factor(f) {}
int operator()(int x) const {
return x * factor;
}
};
// Lambda表达式
auto subtract = [](int a, int b) { return a - b; };
// 使用std::function包装可调用对象
void process(int a, int b, function<int(int, int)> func) {
cout << "结果: " << func(a, b) << endl;
}
// 函数指针数组
using FuncPtr = int(*)(int, int);
vector<function<int(int, int)>> operations;
int main() {
// std::function可以存储任何可调用对象
function<int(int, int)> f1 = add;
function<int(int, int)> f2 = Multiplier(5);
function<int(int, int)> f3 = subtract;
function<int(int, int)> f4 = [](int a, int b) { return a * b; };
cout << "add: " << f1(10, 20) << endl;
cout << "multiply by 5: " << f2(10) << endl;
cout << "subtract: " << f3(20, 10) << endl;
cout << "multiply: " << f4(10, 20) << endl;
// 作为函数参数
process(10, 20, add);
process(10, 20, Multiplier(3));
process(10, 20, [](int a, int b) { return a / b; });
// 存储多个可调用对象
operations.push_back(add);
operations.push_back([](int a, int b) { return a - b; });
operations.push_back(multiplies<int>());
operations.push_back(Multiplier(2));
for (auto& op : operations) {
cout << op(10, 5) << " ";
}
cout << endl;
return 0;
}
八、成员函数
8.1 成员函数基础
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
// 构造函数
Person(const string& n, int a) : name(n), age(a) {}
// const成员函数(只读)
string getName() const { return name; }
int getAge() const { return age; }
// 非const成员函数(可修改)
void setName(const string& n) { name = n; }
void setAge(int a) { age = a; }
// 静态成员函数
static void printCount() {
cout << "总人数: " << count << endl;
}
// 成员函数重载(const和非const)
const string& getNameRef() const { return name; }
string& getNameRef() { return name; }
private:
static int count;
};
int Person::count = 0;
int main() {
Person p("张三", 25);
// 调用成员函数
p.setName("李四");
cout << "姓名: " << p.getName() << endl;
cout << "年龄: " << p.getAge() << endl;
// 通过指针调用
Person* ptr = &p;
ptr->setAge(30);
cout << "年龄: " << ptr->getAge() << endl;
// 静态成员函数
Person::printCount();
// const对象只能调用const成员函数
const Person cp("王五", 28);
cout << cp.getName() << endl; // OK
// cp.setName("赵六"); // 错误:const对象不能调用非const成员
return 0;
}
8.2 成员函数指针
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Calculator {
public:
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return b != 0 ? a / b : 0; }
// 静态成员函数指针
static int staticAdd(int a, int b) { return a + b; }
};
int main() {
Calculator calc;
// 成员函数指针
int (Calculator::*pFunc)(int, int) = nullptr;
pFunc = &Calculator::add;
cout << "add: " << (calc.*pFunc)(10, 20) << endl;
pFunc = &Calculator::subtract;
cout << "subtract: " << (calc.*pFunc)(20, 10) << endl;
// 通过对象指针调用
Calculator* pCalc = &calc;
pFunc = &Calculator::multiply;
cout << "multiply: " << (pCalc->*pFunc)(10, 20) << endl;
// 静态成员函数指针
int (*pStaticFunc)(int, int) = &Calculator::staticAdd;
cout << "staticAdd: " << pStaticFunc(10, 20) << endl;
// 成员函数指针数组
using MemberFunc = int (Calculator::*)(int, int);
vector<MemberFunc> funcs = {
&Calculator::add,
&Calculator::subtract,
&Calculator::multiply,
&Calculator::divide
};
for (auto& func : funcs) {
cout << (calc.*func)(10, 5) << " ";
}
cout << endl;
return 0;
}
九、友元函数
#include <iostream>
#include <string>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 成员函数
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 友元函数(非成员)
friend Complex operator-(const Complex& a, const Complex& b);
// 友元函数(全局函数)
friend ostream& operator<<(ostream& os, const Complex& c);
// 友元类
friend class ComplexPrinter;
};
// 全局友元函数实现
Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.real - b.real, a.imag - b.imag);
}
ostream& operator<<(ostream& os, const Complex& c) {
os << c.real;
if (c.imag >= 0) os << "+";
os << c.imag << "i";
return os;
}
class ComplexPrinter {
public:
void print(const Complex& c) {
// 可以访问Complex的私有成员
cout << "Real: " << c.real << ", Imag: " << c.imag << endl;
}
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex sum = c1 + c2;
Complex diff = c1 - c2;
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
cout << "sum = " << sum << endl;
cout << "diff = " << diff << endl;
ComplexPrinter printer;
printer.print(c1);
return 0;
}