Chinaunix

标题: 请教成员函数指针 [打印本页]

作者: beginer1    时间: 2007-03-22 20:03
标题: 请教成员函数指针
我明明以在类中定义了成员函数指针,可编译时出错,提示pH不存在?帮忙给我指出错误,谢谢.
#include <iostream>
using namespace std;
class Plot{
      public:
            
             void (Plot::*pH)();
      publiclot(){pH=&lot::hello;}
      private:
              void hello()
              {cout<<"call private function"<<endl;
              }
};                    
int main()
{ Plot obj;
  (obj.*pH)();
}
作者: beginer1    时间: 2007-03-22 20:07
哦,原码是这样的.
#include <iostream>
using namespace std;
class Plot{
      public:
            
             void (Plot::*pH)();
      public:
             Plot()
             {pH=&Plot::
                        hello;}
      private:
              void hello()
              {cout<<"call private function"<<endl;
              }
};                    
int main()
{ Plot obj;
  (obj.*pH)();
}
作者: zhujiang73    时间: 2007-03-22 21:32
标题: 回复 2楼 beginer1 的帖子

  1. #include <iostream>
  2. using namespace std;
  3. class Plot
  4. {
  5.       public:            
  6.              typedef void (Plot::*pH)();
  7.              pH  ph;
  8.       public:
  9.              Plot(){ph=&Plot::hello;}
  10.       private:
  11.              void hello()
  12.              {
  13.                       cout<<"call private function"<<endl;
  14.              }
  15. };                    

  16. int main()
  17. {
  18.         Plot obj;
  19.         (obj.*(obj.ph))();
  20. }

复制代码


不过用指针调用私有函数破坏了对象的封装。
作者: beginer1    时间: 2007-03-23 14:02
呵呵,zhujiang73你好厉害呀! 看川了我的意图,我就是要用成员函数指针破坏对象的封装,用成员指针访问私有函数!!
你的代码编译通过了,可我的好象也没错怎么就不行?
作者: beginer1    时间: 2007-03-23 14:19
呵呵,在你的代码提示下,终于找到错误了,我的代码编译通过了,原码如下:

#include <iostream>
using namespace std;
class Plot{
      public:
            
             void (Plot::*pH)();
      public:
             Plot()
             {pH=&Plot::
                                hello;}
      private:
              void hello()
              {cout<<"call private function"<<endl;
              }
};                    
int main()
{ Plot obj;
  (obj.*(obj.pH))();
  cin.get();
}




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2