函數(shù)指針(全局函數(shù)/類成員函數(shù))、函數(shù)對象(Function object)
一. 函數(shù)指針類型為全局函數(shù).
以下是引用片段:
#include "stdafx.h"
#include
using namespace std;
class TestAction;
typedef void (*fp)(int);
void Drink(int i)
{
cout<<"No. "<
}
void Eat(int i)
{
cout<<"No. "<
}
class TestAction
{
public:
fp testAct;
void TestAct(int i)
{
if (testAct != NULL)
{
testAct(i);
}
}
};
int main(int argc, char* argv[])
{
TestAction doact;
doact.testAct = &Drink;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
doact.testAct = &Eat;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
return 0;
}
二. 函數(shù)指針類型為類成員函數(shù).
以下是引用片段:
#include "stdafx.h"
#include
using namespace std;
class Action;
class TestAction;
// 函數(shù)指針類型為類 Action 的成員函數(shù)
typedef void (Action::*fp)(int);
class Action
{
public:
void Drink(int i)
{
cout<<"No. "<
}
void Eat(int i)
{
// 本文轉(zhuǎn)自 C++Builder 研究 - http://www.ccrun.com/article.asp?i=1005&d=sc37og
cout<<"No. "<
}
};
class TestAction
{
public:
// 定義一個函數(shù)指針
fp testAct;
//Action 對象實例 , 該指針用于記錄被實例化的 Action 對象
Action * pAction;
void TestAct(int i)
{
if ((pAction != NULL) && (testAct != NULL))
{
// 調(diào)用
(pAction->*testAct)(i);
}
}
};
int main(int argc, char* argv[])
{
Action act;
TestAction doact;
doact.pAction = &act;
doact.testAct = Action::Drink;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
doact.testAct = Action::Eat;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
return 0;
}
一. 函數(shù)指針類型為全局函數(shù).
以下是引用片段:
#include "stdafx.h"
#include
using namespace std;
class TestAction;
typedef void (*fp)(int);
void Drink(int i)
{
cout<<"No. "<
}
void Eat(int i)
{
cout<<"No. "<
}
class TestAction
{
public:
fp testAct;
void TestAct(int i)
{
if (testAct != NULL)
{
testAct(i);
}
}
};
int main(int argc, char* argv[])
{
TestAction doact;
doact.testAct = &Drink;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
doact.testAct = &Eat;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
return 0;
}
二. 函數(shù)指針類型為類成員函數(shù).
以下是引用片段:
#include "stdafx.h"
#include
using namespace std;
class Action;
class TestAction;
// 函數(shù)指針類型為類 Action 的成員函數(shù)
typedef void (Action::*fp)(int);
class Action
{
public:
void Drink(int i)
{
cout<<"No. "<
}
void Eat(int i)
{
// 本文轉(zhuǎn)自 C++Builder 研究 - http://www.ccrun.com/article.asp?i=1005&d=sc37og
cout<<"No. "<
}
};
class TestAction
{
public:
// 定義一個函數(shù)指針
fp testAct;
//Action 對象實例 , 該指針用于記錄被實例化的 Action 對象
Action * pAction;
void TestAct(int i)
{
if ((pAction != NULL) && (testAct != NULL))
{
// 調(diào)用
(pAction->*testAct)(i);
}
}
};
int main(int argc, char* argv[])
{
Action act;
TestAction doact;
doact.pAction = &act;
doact.testAct = Action::Drink;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
doact.testAct = Action::Eat;
doact.TestAct(0);
doact.TestAct(1);
doact.TestAct(2);
return 0;
}

