函数指针与模板的通用之处

要求a与b之和,c与d之差。。。等等,我们可以单独为他们设置一个函数,但是如果函数功能改变,则需要重写,缺少灵活性。而函数指针与模板提供了极大地便利。

一、函数指针

一个函数在编译时被分配一个入口地址,这个入口地址称为函数指针,就如同指针是一个变量的地址一样。函数指针的用途很多,最常用的就是把指针作为参数传递到其他函数。

#include <iostream>

using namespace std;

int add(int x, int y)//求和
{
    return (x + y);
}
int sub(int x, int y)//求差
{
    return (x - y);
}
void test(int (*p)(int, int), int a, int b)
{//函数指针
    int result = (*p)(a, b);
    cout<<"a = "<<a<<endl;
    cout<<"b = "<<b<<endl;
    cout<<"result = "<<result<<endl;
}
int main()
{
    int a=1, b=2, c=3, d=4;
    test(add, a, b);//利用函数指针求和
    test(sub, c, d);//利用函数指针求差

    return 0;
}

结果:

a = 1
b = 2
result = 3
a = 3
b = 4
result = -1

Process returned 0 (0x0)   execution time : 0.453 s
Press any key to continue.

二、模板

该类程序也可以用静态模板类来实现,解决方法一致。

#include <iostream>

using namespace std;

template <class T>
class Operate
{
public:
    static T add(T x, T y)//求和
    {
        return (x + y);
    }
    static T sub(T x, T y)//求差
    {
        return (x - y);
    }
};

int main()
{
    int a=1, b=2, c=3, d=4;
    int x, y;
    x = Operate<int>::add(a, b);//
    y = Operate<int>::sub(c, d);//
    cout<<x<<endl<<y<<endl;

    return 0;
}

也可以写成先实例化的形式:

#include <iostream>

using namespace std;

template <class T> class Operate
{
public:
    static T add(T x, T y)//求和
    {
        return (x + y);
    }
    static T sub(T x, T y)//求差
    {
        return (x - y);
    }
};

int main()
{
    Operate<int> ope;//实例化
    int a=1, b=2, c=3, d=4;
    int x, y;
    x = ope.add(a, b);//
    y = ope.sub(c, d);//
    cout<<x<<endl<<y<<endl;

    return 0;
}

结果:

3
-1

Process returned 0 (0x0)   execution time : 0.211 s
Press any key to continue.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值