【问题标题】:Accessing member method from a for_each cycle with pointers使用指针从 for_each 循环访问成员方法
【发布时间】:2012-10-27 20:02:12
【问题描述】:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

class A{
  public:
    A():n(4),d(6.6),f(2.7),s("hello my dear"){}
    ~A(){}
    void printAll()
    {
      std::cout << this->n << "\n" << this->d << "\n" << this->f << "\n" << this->s << "\n\n";
    }
  private:
    int n;
    double d;
    float f;
    std::string s;
};

int main(){
  std::vector<A*> v(100);
  //filling v ...
  std::for_each(v.begin(), v.end(), mem_fun_ref(&A*::printAll)); // this isn't supposed to work ?
  return(0);
}

我已经尝试了很多解决方案,这只是最后一个,这些都不起作用,我的目标是为 C++ 11 之前的 C++ 版本提供解决方案,所以我想避免使用 lambda(我也不使用 lambda 进行这项工作没有问题,我的问题仅在于 for_each 循环)。

为了清晰和代码可读性,我想避免奇怪的绑定解决方案,这个解决方案也倾向于向程序添加 1 个库。

那么,当引用指向自定义类型的指针时,我如何才能简单地访问 for_each 循环中的方法?

谢谢。

【问题讨论】:

    标签: c++ class methods foreach


    【解决方案1】:

    首先,由于你的向量包含指针,你需要std::mem_fun,而不是std::mem_fun_ref。

    其次,是std::mem_fun,而不仅仅是mem_fun。

    第三,指向成员的正确语法是&amp;A::printAll,而不是&amp;A*::printAll。 * 在那里做什么?

    【讨论】:

      【解决方案2】:

      使用std::mem_fun 创建一个带指针的函数对象。

      如果您使用的是 C++11,则使用 std::mem_fn,如果生成一个函数对象,则采用指针、智能指针和引用。

      std::for_each(v.begin(), v.end(), std::mem_fn(&A::printAll))
      

      【讨论】:

        【解决方案3】:

        您的成员函数的地址是&amp;A::printAll,而不是&amp;A::*printAll。

        std::for_each(v.begin(), v.end(), mem_fun_ref(&A*::printAll)); /
        //                                              ^ error here - not need this *
        

        也许你被定义指向成员函数类型的指针的语法误导了——这个星号是必要的:

        typedef void (A*::PrintAll)();
        

        [更新]
        次要(或主要 - 正如我从您的 cmets 中了解到的)问题是用于在对象指针上调用成员函数的错误函数 - 有关详细信息,请参阅 AndreyT 答案

        【讨论】:

        • 成员函数的地址 always 需要 &amp; 运算符:&amp;A::printAll。
        • 现在可以了,谢谢,但我从来没有在%A::*printAll 中写过这个%A
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 1970-01-01
        相关资源
        最近更新 更多