C++調(diào)試追蹤class成員變量的方法
比如:int (*foo)(int arg),記住要和另一個指針函數(shù)區(qū)分開來,類似這樣:int *foo(int arg).
比如我們可以這樣聲明一個變量和函數(shù):
int (*pfun)(int arg)=0;
int fun(int arg); //這個函數(shù)實(shí)現(xiàn)隨便啦,我就不寫了。
如果我們想利用函數(shù)指針操作函數(shù),就和指針變量使用一樣:
pfun=fun;
int result=(*pfun)(123);
對,很雞肋也沒必要。這是當(dāng)然,因?yàn)槲覀儧]用在對的地方。下面我要講的是利用一個類去call back另一個無關(guān)類的成員。
代碼:
#include <iostream>
using namespace std;
template<typename T,typename N>
class Functor{
public:
Functor(T *otherp,N (T::*otherfun)(N arg))
{
mp=otherp;
mfun=otherfun;
}
virtual N operator()(N arg)
{
return (*mp.*mfun)(arg);
}
private:
N (T::*mfun)(N arg);
T *mp;
};
class A{
public:
A(int a0):a(a0){}
int traced(int b)
{
cout<<"Trace a="<<a<<",b="<<b<<endl;
return 0;
}
private:
int a;
};
int main()
{
A a(10);
Functor<A,int> trace(&a,&A::traced);
trace(5);
return 0;
}
第33行把class A的成員函數(shù)地址傳給了Functor的函數(shù)指針,從而能夠通過Functor的成員處理A中的成員。
這里用到了對operator()的重載,可以換成別的函數(shù)處理Functor的函數(shù)指針
(不處理也行,但是函數(shù)指針很繞人,不直觀),像這樣:
#include <iostream>
using namespace std;
template<typename T,typename N>
class Functor{
public:
Functor(T *otherp,N (T::*otherfun)(N arg))
{
mp=otherp;
mfun=otherfun;
}
virtual N out(N arg) //改動
{
return (*mp.*mfun)(arg);
}
private:
N (T::*mfun)(N arg);
T *mp;
};
class A{
public:
A(int a0):a(a0){}
int traced(int b)
{
cout<<"Trace a="<<a<<",b="<<b<<endl;
return 0;
}
private:
int a;
};
int main()
{
A a(10);
Functor<A,int> trace(&a,&A::traced);
trace.out(5); //改動
return 0;
}
C++確實(shí)復(fù)雜,但是我們?nèi)绻煤?,?fù)雜就是強(qiáng)大。
相關(guān)文章
C++實(shí)現(xiàn)二叉樹非遞歸遍歷方法實(shí)例總結(jié)
這篇文章主要介紹了C++實(shí)現(xiàn)二叉樹非遞歸遍歷方法實(shí)例總結(jié),是算法設(shè)計(jì)中比較經(jīng)典的一個遍歷算法,需要的朋友可以參考下2014-08-08C++控制臺實(shí)現(xiàn)密碼管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++控制臺實(shí)現(xiàn)密碼管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-11-11C++類模板與函數(shù)模板基礎(chǔ)詳細(xì)講解
C++語言的模板技術(shù)包括函數(shù)模板和類模板,模板技術(shù)是一種代碼重用技術(shù),函數(shù)和類是C++語言中兩種主要的重用代碼形式,這篇文章主要介紹了C++函數(shù)模板和類模板,需要的朋友可以參考下2022-08-08數(shù)組中求第K大數(shù)的實(shí)現(xiàn)方法
本篇文章是對數(shù)組中求第K大數(shù)的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05