日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

[C++11]可调用对象

發布時間:2023/12/4 c/c++ 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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]可调用对象的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。