C++怎么使用委托
时间: 2024-02-05 18:11:56 浏览: 17
在 C++ 中,委托通常是通过函数指针或函数对象来实现的。以下是使用函数指针实现委托的示例代码:
```c++
#include <iostream>
// 声明一个委托类型
typedef int (*Delegate)(int, int);
// 一个加法函数
int add(int x, int y) {
return x + y;
}
// 一个减法函数
int sub(int x, int y) {
return x - y;
}
// 接收一个委托作为参数
int doMath(int x, int y, Delegate delegate) {
return delegate(x, y);
}
int main() {
// 使用加法函数进行计算
int result = doMath(10, 5, add);
std::cout << "10 + 5 = " << result << std::endl;
// 使用减法函数进行计算
result = doMath(10, 5, sub);
std::cout << "10 - 5 = " << result << std::endl;
return 0;
}
```
在上面的示例中,我们通过 `typedef` 关键字定义了一个委托类型 `Delegate`,它是一个函数指针类型,接收两个 `int` 类型的参数并返回一个 `int` 类型的值。然后我们定义了两个函数 `add` 和 `sub`,它们分别实现加法和减法运算。最后,我们定义了一个 `doMath` 函数,它接收三个参数:两个整数和一个委托类型的函数指针。在 `doMath` 函数中,我们通过调用委托来执行相应的数学运算。
除了使用函数指针,还可以使用函数对象来实现委托。以下是使用函数对象实现委托的示例代码:
```c++
#include <iostream>
// 声明一个委托类型
template <typename T>
class Delegate {
public:
virtual T operator()(T, T) = 0;
};
// 一个加法函数对象
template <typename T>
class AddDelegate : public Delegate<T> {
public:
T operator()(T x, T y) override {
return x + y;
}
};
// 一个减法函数对象
template <typename T>
class SubDelegate : public Delegate<T> {
public:
T operator()(T x, T y) override {
return x - y;
}
};
// 接收一个委托作为参数
template <typename T>
T doMath(T x, T y, Delegate<T>& delegate) {
return delegate(x, y);
}
int main() {
// 使用加法函数对象进行计算
AddDelegate<int> addDelegate;
int result = doMath(10, 5, addDelegate);
std::cout << "10 + 5 = " << result << std::endl;
// 使用减法函数对象进行计算
SubDelegate<int> subDelegate;
result = doMath(10, 5, subDelegate);
std::cout << "10 - 5 = " << result << std::endl;
return 0;
}
```
在上面的示例中,我们定义了一个委托类型 `Delegate`,它是一个函数对象类型,接收两个模板类型的参数并返回一个模板类型的值。然后我们定义了两个函数对象 `AddDelegate` 和 `SubDelegate`,它们分别实现加法和减法运算。最后,我们定义了一个 `doMath` 函数,它接收三个参数:两个模板类型的值和一个委托类型的函数对象的引用。在 `doMath` 函数中,我们通过调用委托来执行相应的数学运算。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)