gpt4 book ai didi

c++ - 为什么成员函数需要 '&'(例如在 std::bind 中)?

转载 作者:太空狗 更新时间:2023-10-29 20:28:26 25 4
gpt4 key购买 nike

当我使用 C++11 标准的 std::bind 时,我认识到编译器允许以下内容:

class Foo
{
public:
void F();
int G(int, int);
};

void Foo::F()
{
auto f = bind(&Foo::G, this, _1, _2);
cout << f(1,2) << endl;
}

int Foo::G(int a, int b)
{
cout << a << ',' << b << endl;
return 666;
}

但是如果我在 bind 行中删除 Foo::G 前面的 '&',我会得到一些编译器错误(使用 MinGW 4.7) .

为什么 Foo::G 作为指向成员函数的指针无效,尽管 H&H 都适用于“通常” “函数?

LG 电源

最佳答案

& 需要获取成员函数的地址,一些编译器允许您省略相同的地址,但它是非标准的,有时会造成混淆。

您可以在此处阅读有关成员函数指针的信息: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

关于c++ - 为什么成员函数需要 '&'(例如在 std::bind 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13260332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com