如何将 class 方法作为参数传递给另一个 class 方法
How to pass class method as an argument to another class method
我正在学习 C++,我想知道如何将 class 方法作为参数传递给另一个 class 方法。这是我现在拥有的:
class SomeClass {
private:
// ...
public:
AnotherClass passed_func() {
// do something
return another_class_obj;
}
AnotherClassAgain some_func(AnotherClass *(func)()) {
// do something
return another_class_again_obj;
}
void here_comes_another_func() {
some_func(&SomeClass::passed_func);
}
};
然而,这段代码给出了错误:
cannot initialize a parameter of type 'AnotherClass *(*)()' with an rvalue of type 'AnotherClass (SomeClass::*)()': different return type ('AnotherClass *' vs 'AnotherClass')
谢谢!!
指向SomeClass::passed_func
的成员函数指针的类型是AnotherClass (SomeClass::*)()
。它不是指向自由函数的指针。成员函数指针需要一个对象被调用,特殊语法(->*
):
struct AnotherClass{};
struct AnotherClassAgain{};
class SomeClass {
private:
// ...
public:
AnotherClass passed_func() {
// do something
return {};
}
AnotherClassAgain some_func(AnotherClass (SomeClass::*func)()) {
(this->*func)();
// do something
return {};
}
void here_comes_another_func() {
some_func(&SomeClass::passed_func);
}
};
我正在学习 C++,我想知道如何将 class 方法作为参数传递给另一个 class 方法。这是我现在拥有的:
class SomeClass {
private:
// ...
public:
AnotherClass passed_func() {
// do something
return another_class_obj;
}
AnotherClassAgain some_func(AnotherClass *(func)()) {
// do something
return another_class_again_obj;
}
void here_comes_another_func() {
some_func(&SomeClass::passed_func);
}
};
然而,这段代码给出了错误:
cannot initialize a parameter of type 'AnotherClass *(*)()' with an rvalue of type 'AnotherClass (SomeClass::*)()': different return type ('AnotherClass *' vs 'AnotherClass')
谢谢!!
指向SomeClass::passed_func
的成员函数指针的类型是AnotherClass (SomeClass::*)()
。它不是指向自由函数的指针。成员函数指针需要一个对象被调用,特殊语法(->*
):
struct AnotherClass{};
struct AnotherClassAgain{};
class SomeClass {
private:
// ...
public:
AnotherClass passed_func() {
// do something
return {};
}
AnotherClassAgain some_func(AnotherClass (SomeClass::*func)()) {
(this->*func)();
// do something
return {};
}
void here_comes_another_func() {
some_func(&SomeClass::passed_func);
}
};