C++函数知识点大全(三)

简介: 教程来源 http://htnus.cn/category/software-apps.html 本节详解C++函数对象(仿函数)、std::function、成员函数及友元机制:涵盖自定义函数对象(带状态/谓词/比较)、标准库预定义函数对象(plus、greater等)、std::function统一包装函数/lambda/对象;深入成员函数const属性、静态成员、指针调用;以及友元函数与友元类突破封装限制的用法。

七、函数对象

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;
}

来源:
http://htnus.cn/category/tech-trends.html

相关文章
|
20小时前
|
安全 C语言 C++
C++函数知识点大全(四)
教程来源 https://xcfsr.cn/category/software-dev.html 本文系统讲解C++函数核心特性:虚函数与多态(含纯虚函数、虚析构)、虚函数表机制、异常处理(noexcept、异常安全设计)、以及函数最佳实践(const引用、移动语义、默认参数、单一职责等),涵盖从基础到高级的完整知识体系。
|
1天前
|
人工智能 JSON 监控
Claude Code 源码泄露:一份价值亿元的 AI 工程公开课
我以为顶级 AI 产品的护城河是模型。读完这 51.2 万行泄露的源码,我发现自己错了。
1893 6
|
13天前
|
JavaScript 前端开发 API
VUE前端初级新手知识大全(一)
教程来源 https://app-a6nw7st4g741.appmiaoda.com/ Vue.js是轻量、易上手的渐进式前端框架,专注视图层,支持声明式编程与MVVM模式。本文系统讲解入门知识:从CDN/CLI环境搭建、核心语法(插值、指令、ref/reactive)、响应式原理,到计算属性与侦听器,助你快速构建首个Vue应用。
|
4月前
|
安全 Java API
Java日期处理完全指南(新手也能轻松掌握的Java时间格式化与日期API教程)
教程来源https://www.vpshk.cn/本文介绍Java 8引入的java.time包,详解LocalDateTime、LocalDate等类的使用,涵盖获取当前时间、格式化、解析字符串及日期运算,助你轻松掌握现代Java日期处理方法,适合初学者快速上手。
|
1天前
|
存储 人工智能 安全
静态数据安全治理:存储数据泄露防护系统全解析
企业数据泄露常源于被忽视的静态存储数据。安得卫士SDLP系统以AI智能扫描为核心,实现敏感数据全域发现、自动分类分级、加密隔离、违规处置与全生命周期审计追溯,助力企业摸清数据资产、精准防护、合规达标、溯源取证,筑牢数据安全“最后一道防线”。(239字)
29 4
|
1天前
|
数据采集 监控 JavaScript
电商效率神器!Open Claw对接1688接口,全自动监控选品教程(附完整源码)
电商人苦1688选品久矣!手动翻页、比价、盯库存,耗时易错。本文提供开箱即用方案:用Open Claw官方接口5分钟接入,无需爬虫、不惧反爬,一键获取标题、价格、SKU、库存、销量等全量数据。附完整Python代码,复制配置即可运行,支持自动监控、智能选品、批量比价,个人卖家/工作室/跨境采购皆可高效落地。(239字)
|
1天前
|
安全 数据可视化 物联网
技术解析:基于数字孪生融合引擎的WSBK赛道数字孪生系统构建方案
张雪机车WSBK葡萄牙站夺冠,引爆赛道数字化关注。本文介绍基于数字孪生融合引擎构建专业赛车场3D孪生系统的技术路径,突破高精度建模、实时数据映射、安全仿真与多端交付四大难点,实现L3-L4级微观仿真与毫秒级同步,为赛车运动提供可复用的数字化范式。(239字)
|
1天前
|
缓存 自然语言处理 JavaScript
6款免费pdf解锁软件,PDF解锁工具MATLAB实现库
该项目为PDF文件处理工具,提供合并、拆分等编辑功能,采用MATLAB作为核心开发平台,实现便捷的文档操作与管理。
|
16小时前
|
自然语言处理 监控 JavaScript
聊天记录生成器网页版,对话流生成器Skyrim Script引擎
该项目为《上古卷轴5》游戏开发脚本引擎,支持自动化任务与自定义功能扩展,技术栈基于Python与游戏原生脚本系统。
|
1天前
|
JSON 编解码 Dart
解密大师app,数据解析Dart引擎
基于Dart开发的解析引擎,用于高效解析捷米达APP数据,支持跨平台应用开发,提升数据处理与集成效率。