首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

类成员函数指针有关问题,

2012-04-17 
类成员函数指针问题,急!classA{public:typedefvoid(A::*FPTR)()voidfun1(){cout A::fun1 endl

类成员函数指针问题,急!
class   A  
{
public:
typedef   void   (A::*FPTR)(   );
void     fun1()
{
cout < < "A::fun1 " < <endl;
}
void   fun2   ()
{
cout < < "A::fun2 " < <endl;
}
void   set(int   i);
void   call(){
m_pFunPtr();
}
private:
FPTR   m_pFunPtr;
};

void   A::set(int   i)
{
if(   i   =   1)
m_pFunPtr   =   fun1;
else
m_pFunPtr   =   fun2;
}

int   main()
{
A   a;
a.set(1);
a.call();
system( "pause ");
return   0;
}

编译错误:\main.cpp(19):   error   C2064:   项不会计算为接受   0   个参数的函数
为什么在成员函数中不能调用   m_pFunPtr()   ?

[解决办法]
两个问题,指向成员函数的指针语法错误,if判断的==写成了=
#include "stdafx.h "
#include <iostream>

using namespace std;

class A
{
public:
typedef void (A::*FPTR)( );
void fun1()
{
cout < < "A::fun1 " < <endl;
}
void fun2 ()
{
cout < < "A::fun2 " < <endl;
}
void set(int i);
void call()
{
(this-> *m_pFunPtr)();
}
private:
FPTR m_pFunPtr;
};

void A::set(int i)
{
if( i == 1)
m_pFunPtr = fun1;
else
m_pFunPtr = fun2;
}

int main(int argc, char* argv[])
{
A a;
a.set(2);
a.call();
system( "pause ");
return 0;
}
[解决办法]
1:) "private: " 不是问题.他没有错.
2:) if( i = 1) 错了, 应该 ==
3:) void A::set(int i) 有问题, 应该为:
void A::set(int i)
{
if( i == 1)
m_pFunPtr = &A::fun1;
else
m_pFunPtr = &A::fun2;
}

在Linux 下,你的修改的code成功.

#include <iostream>
#include <iterator>
#include <set>
#include <string>
using namespace std;

class A
{
public:
typedef void (A::*FPTR)( );
void fun1()
{
cout < < "A::fun1 " < <endl;
}
void fun2 ()
{
cout < < "A::fun2 " < <endl;
}
void set(int i);
void call()
{
(this-> *m_pFunPtr)();
}

private:
FPTR m_pFunPtr;
};

void A::set(int i)
{
if( i == 1)
m_pFunPtr = &A::fun1;
else
m_pFunPtr = &A::fun2;
}

int main(int argc, char* argv[])
{
A a;
a.set(2);
a.call();
return 0;
}
~
~
~
"4.c " 43L, 462C written
iclx012$ g++ 4.c
iclx012$ ./a.out
A::fun2
iclx012$

热点排行