簡體   English   中英

在 c++ 中有 &func 或 class::func 的用途嗎?

[英]is there a use for &func or class::func in c++?

這似乎不一致。 為什么我們使用 &Example::func 而不是 Example::func? Example::func 或 &exampleFunction 有沒有用處? 似乎我們不能引用 function 以便排除 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;
} 

因為這就是標准定義函數指針的方式。

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.

這不是為(非靜態)成員函數定義的,因為您無法獲得非 static 成員函數的左值。

來自 C++ 標准:

4.3 函數到指針的轉換

  1. function 類型 T 的左值可以轉換為“指向 T 的指針”類型的右值。 結果是指向 function 的指針。

腳注 52:

這種轉換永遠不會應用於非靜態成員函數,因為無法獲得引用非靜態成員 function 的左值。

我認為出於一致性原因,他們寧願只允許 &function,但隱式轉換只是 C 遺產的產物......

關鍵是使用Function Pointers 對於一個非常粗略的示例,假設您有一個 class 具有多個成員變量,您可能需要通過這些成員變量對 class 類型的數組的元素進行排序,如下所示:

struct CL {
    int x, y, z;
};

bool sort_by_x(const CL& obj1, const CL& obj2);
bool sort_by_y(const CL& obj1, const CL& obj2);
bool sort_by_z(const CL& obj1, const CL& obj2);

...

CL obj[100];
...
sort(obj, obj+100, sort_by_x);
...
sort(obj, obj+100, sort_by_y);
...
sort(obj, obj+100, sort_by_z);

這里 std::sort 用於對 CL 對象數組進行排序。 看第三個參數,它的名字是 function。 std::sort function 可以在第三個參數中使用 function 指針,並使用該 function 作為比較器對數組進行排序。 如何定義 sort_by_* 函數以使 std::sort 按預期工作取決於我們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM