雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

C++調(diào)試追蹤class成員變量的方法

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊:

比如:int (*foo)(int arg),記住要和另一個(gè)指針函數(shù)區(qū)分開來,類似這樣:int *foo(int arg).
比如我們可以這樣聲明一個(gè)變量和函數(shù):

復(fù)制代碼 代碼如下:

int (*pfun)(int arg)=0;
int fun(int arg);    //這個(gè)函數(shù)實(shí)現(xiàn)隨便啦,我就不寫了。

如果我們想利用函數(shù)指針操作函數(shù),就和指針變量使用一樣:

復(fù)制代碼 代碼如下:

pfun=fun;
int result=(*pfun)(123);

對(duì),很雞肋也沒必要。這是當(dāng)然,因?yàn)槲覀儧]用在對(duì)的地方。下面我要講的是利用一個(gè)類去call back另一個(gè)無關(guān)類的成員。

代碼:

復(fù)制代碼 代碼如下:

#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中的成員。
這里用到了對(duì)operator()的重載,可以換成別的函數(shù)處理Functor的函數(shù)指針
(不處理也行,但是函數(shù)指針很繞人,不直觀),像這樣:

復(fù)制代碼 代碼如下:

#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)         //改動(dòng)
   {
       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);      //改動(dòng)
    return 0;
}

C++確實(shí)復(fù)雜,但是我們?nèi)绻煤?,?fù)雜就是強(qiáng)大。

上一篇:C++內(nèi)核對(duì)象封裝單實(shí)例啟動(dòng)程序的類

欄    目:C語言

下一篇:C++卸載程序功能示例

本文標(biāo)題:C++調(diào)試追蹤class成員變量的方法

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3907.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有