当前位置 博文首页 > 和我一起学习:c++类成员函数做函数参数

    和我一起学习:c++类成员函数做函数参数

    作者:[db:作者] 时间:2021-08-23 12:41

    类内部的typedef函数声明,属于类成员,在类外声明时必须加类声明作用域(Test::FUNC),且赋值的函数必须为类成员(&Test::Func1)

    下面的类中,Func1和Func2的返回值类型和参数列表都一样,定义的FUNC类似委托类型

    Test.h

    #pragma once
    #include<iostream>
    using namespace std;
    class Test
    {
    public:
    	typedef void (Test::*FUNC)(int);
    	Test();
    	~Test();
    	void Func(FUNC f, int x);
    	void Func1(int x);
    	void Func2(int x);
    };
    
    

    Test.cpp

    #include "Test.h"
    
    
    Test::Test()
    {
    }
    
    
    Test::~Test()
    {
    }
    
    void Test::Func(FUNC f, int x)
    {
    	(this->*f)(x);
    }
    
    void Test::Func1(int x)
    {
    	cout << "Func1:" << x<<endl;
    }
    
    void Test::Func2(int x)
    {
    	cout << "Func2:" << x << endl;;
    }
    
    

    源.cpp

    #include"Test.h"
    int main()
    {
    	Test test;
    	test.Func(&Test::Func1, 1);
    	test.Func(&Test::Func2, 2);
    
    	system("pause");
    }
    

    运行结果

    在这里插入图片描述

    参考文献

    cs