C++ 靜態成員函式 訪問 類成員變數 & 函式指標、函式指標陣列、函式指標陣列指標的使用 & 回撥函式的使用
阿新 • • 發佈:2019-01-02
靜態成員函式可以通過引用類物件訪問類成員變數;
test.h
#ifndef TEST_H
#define TEST_H
class Test
{
public:
Test();
Test( int a, int b );
static void print( Test &test );
private:
int m;
int n;
int sum;
};
#endif // TEST_H
test.cppmain.cpp#include "test.h" #include <iostream> using namespace std; Test::Test() { } Test::Test(int a, int b) { m = a; n = b; sum = m + n; } void Test::print(Test &test) { cout << "m:" << test.m << endl << "n:" << test.n << endl << "sum:" << test.sum << endl; }
#include "test.h" #include <iostream> using namespace std; //宣告函式指標,宣告時注意函式返回值型別及引數型別要保持一致 int (*p)( int, int ); void (*funcp)(); //函式宣告 int add_ret(int a, int b); int add(int a, int b, int (*p)(int, int)); void FileFunc(); void EditFunc(); int main(int argc, char *argv[]) { int a, b; cout << "please enter two number(eg:a b):"; cin >> a >> b; Test test( a, b ); Test::print( test ); //靜態成員函式的呼叫 p = add_ret; //把函式 add_ret 的地址賦給函式指標 p int sum = p( a, b ); //呼叫函式指標 cout << "int (*p)( int, int ):" << sum << endl; sum += add( a, b, p ); //呼叫回撥函式 cout << "int add(int a, int b, int (*p)(int, int)):" << sum << endl; cout << "int (*p)( int, int ):" << endl; funcp = FileFunc; //把函式 FileFunc 的地址賦給函式指標 funcp funcp(); //呼叫函式指標 funcp = EditFunc; //把函式 EditFunc 的地址賦給函式指標 funcp (*funcp)(); //呼叫函式指標 cout << "void(*pfunarr[2])():" << endl; void(*pfunarr[2])(); //函式指標陣列 pfunarr[0] = FileFunc; pfunarr[1] = EditFunc; pfunarr[0](); //函式指標陣列呼叫 pfunarr[1](); cout << "void(*(*ppfunarr)[2])():" << endl; void(*(*ppfunarr)[2])(); ppfunarr = &pfunarr; //函式指標陣列指標賦值 (*ppfunarr)[0](); (*ppfunarr)[1](); return 0; } int add_ret( int a, int b ) { return a + b; } //回撥函式 int add( int a, int b, int (*p)(int , int )) { return (*p)( a, b ); } void FileFunc() { cout << "FileFunc!" << endl; } void EditFunc() { cout << "EditFunc!" << endl; }
輸出如圖所示:
參考文件: