我想获得一个指向我的对象的实例的函数的指针。这里是我的代码:如何将指针传递给C++中的类实例函数?
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
class Dice {
int face;
public:
Dice() {
face = rand() % 6 + 1;
}
int roll() {
face = rand() % 6 + 1;
return face;
}
};
int main()
{
Dice mydice;
vector<int> v(1000);
generate(v.begin(),v.end(),mydice.roll);
}
我的编译器在我吠叫与神秘邮件=的产生线)请指出如何正确地告诉生成调用mydice.roll()
填充矢量v
。
'std :: bind(&Dice :: roll,&mydice);' - 或者只是'[&] {return mydice.roll(); }'。 – Xeo
[C++函数指针(类成员)可能重复到非静态成员函数](http://stackoverflow.com/questions/990625/c-function-pointer-class-member-to-non-static-member-函数) –
@Xeo请使用答案,而不是评论=) – Dima