C++ ist eine kompilierte Sprache. Daher können Sie nicht "die Funktion einer Klasse im laufenden Betrieb ändern". Nur interpretierte Sprachen können das tun.
Hier ist eine Sache oder zwei, die Sie in C++ tun können:
#include <functional> // For std::function
bool IsGreaterThan(int a, int b)
{
return a > b;
}
int main()
{
// 1. Create a lambda function that can be reused inside main()
const auto sum = [](int a, int b) { return a + b;};
int result = sum(4, 2); // result = 6
// 2. Use std::function to use a function as a variable
std::function<bool(int, int)> func = IsGreaterThan;
bool test = func(2, 1); // test = true because 2 > 1
}
Im zweiten Beispiel haben wir einen Funktionszeiger erstellt, der in Argument nimmt zwei int
und gibt einen bool
. Der Vorteil der Verwendung von std :: function ist, dass Sie Zeiger auf Elementfunktionen mit Zeiger auf Funktionen mischen können, solange sie dieselben Argumente und Rückgabewerte haben.
EDIT: Hier ist ein Beispiel, wie Sie Member und Nicht-Member-Funktionen innerhalb eines einzelnen Vektors mit Std :: function und Std :: Bind halten.
bool IsGreaterThan(int a, int b)
{
return a > b;
}
typedef bool(*FunctionPointer)(int, int); // Typedef for a function pointer
// Some class
struct SomeClass
{
private:
vector<FunctionPointer> m_functionPointers;
vector<std::function<bool(int, int)>> m_stdFunctions;
public:
SomeClass()
{
// With regular function pointers
m_functionPointers.push_back(IsGreaterThan);
m_functionPointers.push_back(&this->DoSomething); // C2276: '&' : illegal operation on bound member function expression
// With std::function
m_stdFunctions.push_back(IsGreaterThan);
m_stdFunctions.push_back(std::bind(&SomeClass::DoSomething, this, std::placeholders::_1, std::placeholders::_2)); // Works just fine.
}
bool DoSomething(int a, int b) { return (a == b); }
};
Schauen Sie in Lambda-Funktionen in C++. –
@connor In C++ gibt es Lambda-Ausdrücke und Standardklasse std :: function. –