在一些编程语言中(比如PHP和JavaScript),我可以使用一个变量作为函数。例如:
PHP: Class::$var_function();
这是否有可能在C ++中实现,而不需要使用switch或if语句?
在一些编程语言中(比如PHP和JavaScript),我可以使用一个变量作为函数。例如:
PHP: Class::$var_function();
是的,这样的变量被称为函数指针(非成员或静态成员函数)或指向成员函数的指针(非静态成员函数)。
另外,Boost、C++ TR1和C++11都提供了多态function
包装器,它基本上是一种超级灵活的、通用的、泛型的函数指针类型。
int max(int v1, int v2) { return (v1 > v2) ? v1 : v2; }
int min(int v1, int v2) { return (v1 < v2) ? v1 : v2; }
int add(int v1, int v2) { return v1 + v2; }
int (*function)(int, int) = add;
int x = function(1, 3); // x == 4
function = min;
int y = function(1, 3); // x == 1
Etc.
您也可以在C++中获取成员函数的指针;但是,表示法略有不同。
您可以看到使用以下表示法通过指向函数的指针来调用函数的代码:
function = max;
int z = (*function)(1, 3); // x == 3
这是旧式的、非标准的C语言。但它清楚地表明正在使用指向函数的指针(因此我仍然喜欢它并经常使用它)。
詹姆斯的回答可能是最好的。但是,如果你使用的是c++11兼容的编译器,你可以选择使用std::function。
例如:
#include <functional>
#include <iostream>
typedef std::function<void(int a)> callback_t;
class A {
public:
void fn(int a) { std::cout << a << std::endl; }
};
void fn2(int b) { std::cout << a << std::endl; }
int main() {
A a;
callback_t c = std::bind(&A::fn, a, std::placeholders::_1);
c(1);
c = fn2;
c(2);
return 0;
}
#include <boost/function.hpp>
#include <iostream>
typedef boost::function<void(int a)> callback_t;
class A {
public:
void fn(int a) { std::cout << a << std::endl; }
};
void fn2(int b) { std::cout << a << std::endl; }
int main() {
A a;
callback_t c = boost::bind(&A::fn, a, boost::placeholders::_1);
c(1);
c = fn2;
c(2);
return 0;
}
A a();
不是声明一个返回类A
且不带参数的本地函数吗?我认为你只需要A a;
。 - dreamlaxclass MyClass
{
public:
MyClass(): member(42) {};
void operator()(int i) { std::cout << (member=i) << '\n'; }
void operator()() { std::cout << member++ << '\n'; }
private:
int member;
};
int main()
{
MyClass foo;
foo(); // prints 42
foo(); // prints 43
foo(23); // prints 23
foo(); // prints 24
}