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

相关文章
|
3天前
|
设计模式 Java 开发者
Python架构知识点大全(一)
教程来源 https://htnus.cn/category/artificial-intelligence.html 本文系统解析Python架构核心:从三层架构(用户代码→核心层→内置库→C扩展)、CPython等五大解释器,到对象模型、引用计数与分代GC、内存池机制等底层原理,助开发者深入理解运行机制,提升代码性能与可靠性。
|
4天前
|
安全 C语言 C++
C++函数知识点大全(四)
教程来源 https://xcfsr.cn/category/software-dev.html 本文系统讲解C++函数核心特性:虚函数与多态(含纯虚函数、虚析构)、虚函数表机制、异常处理(noexcept、异常安全设计)、以及函数最佳实践(const引用、移动语义、默认参数、单一职责等),涵盖从基础到高级的完整知识体系。
|
13天前
|
前端开发 JavaScript
JavaScript学习知识点大全(二)
教程来源 https://app-a87ujc988w01.appmiaoda.com/ 本节系统讲解JavaScript核心数据结构与异步编程:涵盖数组(创建、遍历map/filter/reduce、增删改查及高级方法)、Set/Map集合操作与WeakSet/WeakMap弱引用特性;字符串常用方法与正则表达式(匹配、提取、替换及高级语法);以及回调、Promise、async/await异步处理与事件循环机制。
|
安全 网络安全
Foxmail邮箱提示错误:ssl连接错误,errorCode:5解决方法
Foxmail邮箱提示错误:ssl连接错误,errorCode:5解决方法
8674 0
|
13天前
|
存储 JavaScript 前端开发
JavaScript学习知识点大全(三)
教程来源 https://app-aakcgtuh1ywx.appmiaoda.com 本文系统讲解前端核心 DOM/BOM 操作与错误处理:涵盖元素选择、增删改查、属性/样式控制、事件绑定与委托;BOM 中 window、navigator、location、history 及本地存储;以及 try-catch、错误类型识别、全局异常捕获等健壮性实践,助力高效开发。
|
13天前
|
JavaScript 前端开发 开发者
JavaScript学习知识点大全(四)
教程来源 https://app-aaqhxe29haf5.appmiaoda.com 讲解JavaScript模块化(ES6/ CommonJS)、ES6+核心特性(解构、展开符、模板字符串、可选链、BigInt等)及性能优化技巧(内存管理、代码与网络优化),涵盖最佳实践与实用示例,助力开发者构建高效、可维护的现代Web应用。
|
13天前
|
存储 JavaScript 前端开发
JavaScript学习知识点大全(一)
教程来源 https://app-a7illrp9pngh.appmiaoda.com/ 本文系统梳理JavaScript核心知识:从基础语法(变量、数据类型、运算符、流程控制)到函数进阶(作用域、闭包、高阶函数)、面向对象(原型链、Class、继承)等,兼顾ES6+新特性。适合初学者构建完整知识体系,也便于开发者查漏补缺。
|
4天前
|
C++
C++函数知识点大全(二)
教程来源 https://xcfsr.cn/category/open-source.html 本文详解C++核心函数特性:内联函数(`inline`)提升性能、`constexpr`实现编译期计算;函数模板支持泛型编程与特化;可变参数模板与折叠表达式简化多参处理;Lambda表达式提供灵活匿名函数,涵盖捕获机制、泛型参数(`auto`)及`constexpr`支持。内容覆盖C++11至C++17关键特性。
|
4天前
|
C语言 C++ 开发者
C++函数知识点大全(一)
教程来源 https://xcfsr.cn/category/cloud.html 本文系统梳理C++函数核心知识:从基础定义、返回值(含引用/指针/移动语义)、重载规则、默认参数,到现代特性如Lambda、模板函数等,兼顾初学者体系构建与开发者深度参考。
|
12天前
|
缓存 前端开发 网络协议
使用 CDN 给网站加速的保姆级教程:从卡顿到飞一般的体验
CDN 内容分发网络配置全攻略,从开通到生效不到 1 小时,就能让用户体验从 “卡顿” 变 “飞一般流畅”。
558 3

热门文章

最新文章