免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1751 | 回复: 7
打印 上一主题 下一主题

[C++] 请教 函数指针的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-11-23 15:21 |只看该作者 |倒序浏览
#include <iostream>
using namespace std;
class A
{
public:
    typedef int(A::*FUNC)(int);
    A()
    {
        Test(static_cast<A::FUNC>(A::tryy));
    };
    ~A();
   
    void Test(FUNC f)
    {
        cout<<f(5)<<endl; //error C2064: term does not evaluate to a function

    }
    int tryy(int nTimes)
    {
        return nTimes;
    }
};

int main()
{
    A a;
    return 0;
   
}
帮忙改正一下。

论坛徽章:
0
2 [报告]
发表于 2007-11-23 15:37 |只看该作者
#include <iostream>
using namespace std;
class A
{
public:
    typedef int(A::*FUNC)(int);
    A()
    {
        Test(tryy);
    };
    ~A();
   
    void Test(FUNC f)
    {
        f_=f;   
    }
    FUNC getf()
    {
        return f_;
    }
    int tryy(int nTimes)
    {
        return nTimes;
    }
private:
    FUNC f_;
};

int main()
{
    A *a = new A;
    cout<<(a->*(a->getf()))(6);
   
//    cout<<*(a->getf())(6)<<endl;

    return 0;
   
}
这样就可以了,有点晕,不是很明白,哪位可以解释一下,请尽量详细些,多谢。

论坛徽章:
0
3 [报告]
发表于 2007-11-23 16:40 |只看该作者
我晕了

论坛徽章:
0
4 [报告]
发表于 2007-11-23 17:34 |只看该作者
原帖由 zhangchegn 于 2007-11-23 15:21 发表
#include
using namespace std;
class A
{
public:
    typedef int(A::*FUNC)(int);
    A()
    {
        Test(static_cast(A::tryy));
    };
    ~A();
   
    void Test(FUNC f)
    {
...


static int tryy(int nTimes)
{
.....................
}

[ 本帖最后由 web_surf 于 2007-11-23 17:39 编辑 ]

论坛徽章:
0
5 [报告]
发表于 2007-11-23 18:01 |只看该作者
#include <iostream>
using namespace std;
class A
{
public:
  typedef int (A::*FUNC) (int);
    A ()
  {
    Test (static_cast<A::FUNC>A::tryy);  这儿也好像不对
  };
  ~A ();

  void Test (FUNC f)
  {
    cout << *f(5) << endl; 这儿如何修改?


  }
  static int tryy (int nTimes)
  {
    return nTimes;
  }
};

int
main ()
{
  A a;
  return 0;

}
关于this指针传递的问题吧,麻烦说的详细些

论坛徽章:
0
6 [报告]
发表于 2007-11-23 18:13 |只看该作者
1)
typedef int (A::*FUNC) (int); -->
typedef int (*FUNC) (int);

2)
Test (static_cast<A::FUNC>A::tryy) -->
Test (tryy)

3)
*f(5)  -->
f(5)

[ 本帖最后由 web_surf 于 2007-11-23 18:14 编辑 ]

论坛徽章:
0
7 [报告]
发表于 2007-11-23 18:16 |只看该作者

算了,一起写给你吧

#include <iostream>
using namespace std;
class A
{
public:
  typedef int (*FUNC) (int);
    A ()
  {
    Test (tryy);  这儿也好像不对
  };


  void Test (FUNC f)
  {
    cout << f(5) << endl; 这儿如何修改?

  }
  static int tryy (int nTimes)
  {
    return nTimes;
  }
};

int main ()
{
  A a;
  return 0;

}

论坛徽章:
0
8 [报告]
发表于 2007-11-23 18:23 |只看该作者
web_surf,thanks a lot。
tryy是静态成员函数,不需要this指针,搞晕了。明白了,多谢。:wink:
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP