c++ 中 &func 或 class::func 有用途吗?
这似乎不一致。 为什么我们使用 &Example::func 而不是 Example::func? Example::func 或 &exampleFunction 有用途吗? 我们似乎无法引用函数,因此排除了Example::func。 我想不出一种使用 &exampleFunction 的方法,因为 exampleFunction 已经返回了一个指针。
#include <iostream>
class Example {
public:
void func() { std::cout <<"print me\n"; }
};
void exampleFunction() { std::cout << "print me too\n"; }
typedef void (Example::*ExampleFunc_t)();
typedef void (*ExampleFunction_t)();
int main()
{
Example e;
ExampleFunc_t f = &Example::func;
ExampleFunction_t f2 = exampleFunction;
(e.*f)();
f2();
return 0;
}
This seems inconsistent. Why do we use &Example::func instead of Example::func? is there a use for Example::func or &exampleFunction? it doesnt seem like we can make a reference to a function so that rules out Example::func. and i cant think of a way to use &exampleFunction since exampleFunction already returns a pointer.
#include <iostream>
class Example {
public:
void func() { std::cout <<"print me\n"; }
};
void exampleFunction() { std::cout << "print me too\n"; }
typedef void (Example::*ExampleFunc_t)();
typedef void (*ExampleFunction_t)();
int main()
{
Example e;
ExampleFunc_t f = &Example::func;
ExampleFunction_t f2 = exampleFunction;
(e.*f)();
f2();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为这就是标准定义函数指针的方式。
实际上,您始终必须使用地址运算符
&
来获取指向函数的指针,但对于常规函数和静态成员函数,在标准。这不是为(非静态)成员函数定义的,因为您无法获取非静态成员函数的左值。
来自 C++ 标准:
附注52:
我认为出于一致性原因,他们宁愿只允许 &function,但隐式转换只是 C 遗产的产物......
Because that's how the standard defines pointers to functions.
You actually always have to use the address operator
&
to get a pointer to a function, but for regular functions and static member function, an implicit conversion from function to pointer-to-function is defined in the standard.This is not defined for a (non static) memberfunction because you can't obtain an lvalue to a non static memberfunction.
From the C++ standard:
with footnote 52:
I think that they'd rather only allow &function, for consistency reasons, but that the implicit conversion is simply an artifact of the C heritage...
重点是使用函数指针。 举一个非常粗略的示例,假设您有一个具有多个成员变量的类,您可能需要通过这些成员变量对该类类型的数组的元素进行排序,如下所示:
这里 std::sort 用于对 CL 对象的数组进行排序。 看第三个参数,它是一个函数的名称。 std::sort 函数可以在第三个参数中采用函数指针,并使用该函数作为比较器对数组进行排序。 如何定义 sort_by_* 函数以便 std::sort 按预期工作取决于我们。
The point is using Function Pointers. For a very rough example, suppose you have a class having several member variables by which you may need to sort of the elements of an array of that class type, like this:
Here std::sort is used to sort an array of CL objects. Look at the third parameter, it's name of a function. The std::sort function can take a function pointer in third parameter, and use that function as comparator to sort the array. It is upto us how to define sort_by_* functions so that std::sort works as expected.