Solution to C compilation error: 'no match for call to 'function', how to solve it?
When developing using the C programming language, we will inevitably encounter various compilation errors. One of the common errors is "no match for call to 'function'". This error usually occurs when we try to call a function object. This article will explain the causes of this error and provide some solutions.
First, let’s look at a simple example of this error:
#includeclass MyFunctor { public: void operator()(int x) { std::cout << "Hello world! The value of x is: " << x << std::endl; } }; int main() { MyFunctor myFunctor; myFunctor(10); // 编译错误发生在这里 return 0; }
In the above example, we defined a class namedMyFunctor
, which repeats The function call operatoroperator()
is loaded and a message is output in the function. In themain
function, we create an objectmyFunctor
of typeMyFunctor
and try to perform function operations by calling this object. However, when we try to compile this code, we encounter the above compilation error.
The reason for this error is that the C compiler cannot find a matching function to perform the call to the function object. When we try to call a function object, the compiler looks for a function with an overloaded function call operator that matches the call argument type. If no matching function is found, the compiler will report an error.
To solve this error, we can take the following approaches:
class adds an overloaded function that accepts a
constmodified parameter:
class MyFunctor { public: void operator()(int x) { std::cout << "Hello world! The value of x is: " << x << std::endl; } void operator()(const int& x) { std::cout << "Hello world! The value of x is (const ref): " << x << std::endl; } };
constQuote to pass parameters to avoid compilation errors. For example:
int main() { MyFunctor myFunctor; myFunctor(10); // 调用重载函数 void operator()(const int& x) return 0; }
int main() { MyFunctor myFunctor; myFunctor(static_cast(10)); // 显式转换类型为 int return 0; }
int main() { MyFunctor myFunctor; void (MyFunctor::*functionPtr)(int) = &MyFunctor::operator(); (myFunctor.*functionPtr)(10); // 通过函数指针间接调用函数对象的函数调用操作符 return 0; }
The above is the detailed content of How to solve C++ compilation error: 'no match for call to 'function'?. For more information, please follow other related articles on the PHP Chinese website!