华剑缘
一切都在这个过程中获得,将那些目标埋藏于心中
posts - 19,comments - 20,trackbacks - 0
/*
 * GridTest.h
 *
 *  Created on: 2009-2-27
 *      Author: Administrator
 
*/

#ifndef GRIDTEST_H_
#define GRIDTEST_H_

class GridTest {
    
static const int x=3,y=4;
public:
    GridTest();

    
virtual ~GridTest();
    typedef 
int (GridTest:: *memberFuncType)(int x, int y);
    
void display();
    
int foreach(memberFuncType fn, int i, int j);
    
int test1(int x, int y);
    
int test2(int x, int y);
    
int test3(int x, int y);
    
int test4(int x, int y);
};

#endif /* GRIDTEST_H_ */



/*
 * GridTest.cpp
 *
 *  Created on: 2009-2-27
 *      Author: Administrator
 
*/

#include 
"GridTest.h"
#include 
<iostream>
using namespace std;

GridTest::GridTest() {
    
// TODO Auto-generated constructor stub

}


GridTest::
~GridTest() {
    
// TODO Auto-generated destructor stub
}

int GridTest::foreach(memberFuncType fn, int x, int y){
    cout
<<"GridTest::foreach(memberFuncType fn, int x, int y)执行了"<<endl;
    cout
<<"fn(x,y)"<<(this->*fn)(x, y);
    
return (this->*fn)(x, y);
}

int GridTest::test1(int x, int y){
    cout
<<"GridTest::test1(int x, int y)执行了!"<<endl;
    
return 0;
}
int GridTest::test2(int x, int y){
    cout
<<"GridTest::test2(int x, int y)执行了!"<<endl;
    
return 0;
}
int GridTest::test3(int x, int y){
    cout
<<"GridTest::test3(int x, int y)执行了!"<<endl;
    
return 0;
}
int GridTest::test4(int x, int y){
    cout
<<"GridTest::test4(int x, int y)执行了!"<<endl;
    
return 0;
}
void GridTest::display(){
    cout
<< this->foreach( this->test1, 4, 5); 
//一直报错:no matching function for call to `GridTest::foreach(<unknown type>, int, int)'
}

int main()
{
    GridTest 
*grid;
    grid
= new GridTest();
    grid
->display();
    
return 0;
}

这段代码在VC6.0上就没有问题,在Eclipse上编译就报错 no matching function for call to `GridTest::foreach(<unknown type>, int, int)'
}
posted on 2009-03-09 17:14 华剑缘 阅读(1570) 评论(5)  编辑 收藏 引用

FeedBack:
# re: 求助:关于 C++函数指针, 成员函数指针的问题
2009-03-09 17:52 | Kevin Lynx
cout << this->foreach( this->test1, 4, 5);
改为:
cout << this->foreach( &GridTest::test1, 4, 5);

对于C函数来说,函数名直接表示其函数地址,但是对于成员函数而言,则必须使用&ClassName::memFn才表示该成员函数的地址。gcc对C++语法要求更严格。

  回复  更多评论
  
# re: 求助:关于 C++函数指针, 成员函数指针的问题
2009-03-09 21:57 | 陈梓瀚(vczh)
如何通过指针调用成员函数的解决方案:
class A
{
public:
int Method(int x);
};

//1:构造对象A
A a;
//2:拿到函数指针
typedef int (A::*FP)(int);
FP fp=&A::Method();
//3:调用
int result=a.*fp(100);  回复  更多评论
  
# re: 求助:关于 C++函数指针, 成员函数指针的问题
2009-03-09 23:10 | 华剑缘
@Kevin Lynx
谢谢,果然是这样.问题解决了  回复  更多评论
  
# re: 求助:关于 C++函数指针, 成员函数指针的问题
2009-03-09 23:12 | 华剑缘
@陈梓瀚(vczh)
谢谢,讲的很清楚.  回复  更多评论
  
# re: 求助:关于 C++函数指针, 成员函数指针的问题
2009-03-10 01:49 | 陈梓瀚(vczh)
@华剑缘
我认为你应该可以理解为什么《The C++ Programming Language》说“你没见过->*和.*的话也无所谓”了。  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理