我正在嘗試使用顯式取消參考來呼叫函式指標。但是編譯器會拋出一個錯誤:
no operator "*" matches these operands.
這是我的代碼的簡化版本:
#include <functional>
#include <iostream>
int add(int a, int b)
{
return a b;
}
std::function<int(int, int)> passFunction()
{
return &add;
}
int main()
{
int a{ 1 };
int b{ 2 };
std::cout << (*passFunction())(a, b);
return 0;
}
問題是,當我寫的時候它作業得很好:
std::cout << passFunction()(a, b); // without asterix.
這讓我大吃一驚。
我以為,我在函式呼叫中弄亂了括號。我嘗試了不同的順序和優先級,我用 & 號呼叫它,但編譯器仍然沒有退縮。
uj5u.com熱心網友回復:
我正在嘗試使用顯式取消參考來呼叫指標函式。但是編譯器拋出一個
error: 'no operator "*" matches these operands'.
型別很重要!
的回傳型別passFunction不是指標,而是std::function. 這不是可以取消參考的東西。因此,您會收到編譯器錯誤。
問題是,當我寫的時候它作業得很好:
std::cout << passFunction()(a, b);沒有 asterix [...]
std::function用于呼叫/呼叫的意思。這就是為什么passFunction()(a, b)有效。它呼叫operator()of std::function(即等價于passFunction().operator()(a, b))。
話雖如此,如果您只是通過auto(從 C 14 開始 - 讓編譯器推斷型別)回傳函式,您將獲得實際的函式指標,您可以通過取消參考(不必要)或直接呼叫它。
using fun_t = int(*)(int, int); // function pointer type
auto passFunction()
//^^^ use auto --> type == int(*)(int, int)
// or use fun_t
{
return &add;
}
現在你可以(不必要)
(*passFunction())(a, b);
或者
passFunction()(a, b);
現在很明顯的問題是,“這兩種語法怎么可能?” . 在以下帖子中詳細閱讀此處:
- 函式指標的解參考是如何發生的?
- 通過函式指標呼叫函式 - 是否取消參考指標?有什么不同?
- 為什么我們可以取消參考函式指標?
uj5u.com熱心網友回復:
但編譯器拋出錯誤:'沒有運算子“*”匹配這些運算元'。
從它的檔案中我們可以看出,您的passFunction回傳 a which沒有任何多載的取消參考運算子。因此我們不能寫。正確的語法如下所示:std::function<int(int, int)>*passFunction()
//------------v----------------------->removed the * as std::function does not overload any such operator
std::cout << ( passFunction())(a, b)
或者
//----------v------------------------>no need for dereferencing
std::cout << passFunction()(a, b);
uj5u.com熱心網友回復:
您不應該在that回傳上使用*運算子,因為它不回傳需要取消參考的指標。std::function<int(int, int)>passFunction()
這個簡單的例子可以做到:
#include <functional>
#include <iostream>
int add(int a, int b) {
return a b;
}
std::function<int(int, int)> passFunction() {
return add; // or return &add - same thing when it comes to free functions
// as opposed to member functions
}
int main() {
int a{1};
int b{2};
std::cout << passFunction()(a, b);
}
我認為混淆來自您&add回傳函式指標這一事實 - 但看看什么是重要的:回傳型別:
std::function<int(int, int)>
這就是passFunction()回報。它不是一個指標。它按值回傳它。您的函式指標return僅用作std::function<int(int, int)>的建構式的引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524125.html
