[C++11]可调用对象
生活随笔
收集整理的這篇文章主要介紹了
[C++11]可调用对象
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在C++中存在"可調用對象"這么一個概念,準確來說,可調用對象有如下幾種定義:
1.是一個函數指針
代碼如下:
int print(int a, double b) {cout << a << b << endl;return 0; }int(*func)(int, double) = &print;2.是一個具有operator()成員函數的類對象(仿函數)
代碼如下:
#include <vector> #include <iostream> #include <string>using namespace std;using func_ptr = void(*)(int, string);struct Test {void operator()(int x){cout << "x = " << x << endl;} };int main() {Test t1;t1(19);return 0; }測試結果:
3.是一個可被轉換為函數指針的類對象
代碼如下:
#include <vector> #include <iostream> #include <string>using namespace std;using func_ptr = void(*)(int, string);struct Test {static void print(int a, string b){cout << "name = " << b << ",age = " << a << endl;}//將類對象轉換成函數指針operator func_ptr(){return print;//需要是靜態函數} };int main() {Test t1;t1(19, "nihao");return 0; }測試結果:
4.是一個類成員函數指針或者類成員指針
代碼如下:
#include <vector> #include <iostream> #include <string>using namespace std;using funcptr = void(*)(int, string);struct Test {static void print(int a, string b){cout << "name = " << b << ",age = " << a << endl;}void hello(int a, string b){cout << "name = " << b << ",age = " << a << endl;}int id = 520;};int main() {Test t1;funcptr f = Test::print;//類的函數指針using fptr = void(Test::*)(int, string);fptr f1 = &Test::hello;//類的成員指針(變量)using ptr1 = int Test::*;ptr1 pt = &Test::id;Test ttt;(ttt.*f1)(20, "tom");ttt.*pt = 100;cout << "id = " << ttt.id << endl;return 0; }測試結果:
總結
以上是生活随笔為你收集整理的[C++11]可调用对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果备份用什么软件
- 下一篇: 数字转换为中文大写金额,我用了2小时,同