简体   繁体   English

通过指针访问非静态类成员函数的澄清

[英]Clarification with accessing non-static class member function via pointer

I am having difficulty accessing a non-static member function from a function pointer and can't quite figure out my syntax issue. 我无法从函数指针访问非静态成员函数,并且无法完全弄清楚我的语法问题。 When attempting to compile as seen below I receive "error: fnc_ptr not declared in this scope." 当尝试编译时,如下所示,我收到“错误:fnc_ptr未在此范围内声明。” and when if the code is modified to not access the function it should point to it compiles and will print out 1 for bar.fn_ptr .To compile I used: 如果代码被修改为不访问该函数,它应该指向它编译并将打印出1为bar.fn_ptr。编译我使用:

g++ -std=c++11 -Wall example.cpp foo.cpp

The split file structure/namespace is just meant to emulate the same conditions as my original issue. 拆分文件结构/命名空间只是为了模拟与原始问题相同的条件。

example.cpp example.cpp

#include "foo.h"
#include <iostream>

int main(int argc, char* argv[]){

  pizza::foo bar;
  bar.fn_ptr = &pizza::foo::fnc_one;
  std::cout << (bar.*fn_ptr)(1) << std::endl;

  return 0;
}

foo.cpp Foo.cpp中

#include <cmath>
#include "foo.h"

namespace pizza{

   double foo::fnc_one(double x){
        return pow(x,3) - x + 2;
   }
}

foo.h foo.h中

namespace pizza{

   class foo{
       public:
        double (foo::*fn_ptr)(double);
        double fnc_one(double);

        foo(){
           fn_ptr = 0;
        }
   };
}

A very similar question can be found here , with additional reference here . 一个非常类似的问题,可以发现在这里 ,另外参考这里

You are missing bar. 你错过了bar. when referring to fn_ptr which is an attribute of that object. 当引用fn_ptr ,它是该对象的属性。 Change it to: 将其更改为:

  std::cout << (bar.*(bar.fn_ptr))(1) << std::endl;

And it works. 它有效。

I also recommend reading this FAQ on the subject: https://isocpp.org/wiki/faq/pointers-to-members 我还建议您阅读以下主题的常见问题解答: https//isocpp.org/wiki/faq/pointers-to-members

I believe the correct syntax is: 我相信正确的语法是:

//std::cout << (bar.*fn_ptr)(1) << std::endl;
std::cout << (bar.*(bar.fn_ptr))(1) << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM