【C++学习】函数指针

#include<iostream> //包含头文件
using namespace std; 
void func(int no, string str){
    cout << "亲爱的"<< no << "号:" << str << endl;
}

int main(){
    int bh = 3;
    string message = "我是一只傻傻鸟";
    func(bh, message);
    void(*pfunc)(int,string); //声明函数的函数指针
    pfunc = func;
    pfunc(bh,message); // c++的方式 用函数指针名调用函数。
    void(*pfunc1)(int,string) = func; 
    pfunc1(bh,message); 
    (*pfunc)(bh,message); //用函数指针名调用函数,C语言
}

函数指针的应用场景,主要是用于回调,用个函数指针,调用方自己实现函数的内容,但调用方式和入参由自己定义。

#include<iostream> //包含头文件
using namespace std; 
void func(int no, string str){
    cout << "亲爱的"<< no << "号:" << str << endl;
}

void ls(){
    cout << "我是ls的表白方式:" << "对你爱爱爱不完" << endl;
}

void zs(){
    cout << "我是zs的表白方式:" << "他一定很爱你" << endl;
}

void ls(int a){
    cout << "我是ls的表白方式:" << "对你爱爱爱不完:" << a << endl;
}

void zs(int a){
    cout << "我是zs的表白方式:" << "他一定很爱你:" << a << endl;
}
void show(void(*pf)()){
    cout << "表白之前的准备工作完成。\n";
    pf();
    cout << "表白之后的收尾工作已完成。\n";
}

void show(void(*pf)(int),int a){
    cout << "表白之前的准备工作完成。\n";
    pf(a);
    cout << "表白之后的收尾工作已完成。\n";
}
int main(){
    int bh = 3;
    string message = "我是一只傻傻鸟";
    func(bh, message);
    void(*pfunc)(int,string); //声明函数的函数指针
    pfunc = func;
    pfunc(bh,message); // c++的方式 用函数指针名调用函数。
    void(*pfunc1)(int,string) = func; 
    pfunc1(bh,message); 
    (*pfunc)(bh,message); //用函数指针名调用函数,C语言
    
    cout << "===============" << endl;
    // 不传参的方式
    show(ls); //李四要表白
    show(zs); // 张三要表白
    // 传参的方式
    cout <<"-------------------"<< endl;
    show(ls,3);
    show(ls,4);
}

猜你喜欢

转载自blog.csdn.net/weixin_40293999/article/details/132596055