返回C++类中的函数指针

Return Function Pointer in C++ Class

本文关键字:函数 指针 C++ 返回      更新时间:2023-10-16

这是我编写的c++源代码。我想做的是运行类a的成员函数init((,get_func返回a((、b((、c((、d((中函数的地址。最后,func((被执行,我希望看到b。它看起来很简单,但现在这个问题困扰着我。

编译器给出以下错误:-未在此范围中声明"choice"-未在此作用域中声明"a"返回a((;-对"A::init(char("的调用没有匹配的函数a.init('b'(;

我错过了什么?

#include <iostream>
class A {
private:
int (A::*get_func())();
int a(){printf("a");}
int b(){printf("b");}
int c(){printf("c");}
int d(){printf("d");}
public:
A();
~A();
int init();
char choice;
}
A::init(char ch) {
this->choice = ch;
int (A::*func)() = get_func();
func();
}
int (A::*get_func())() {
switch(choice) {
case 'a' :
return a;
case 'b' :
return b;
case 'c' :
return c;
case 'd' :
return d;
}
}
int main() {
A a;
a.init('b');
}

这应该可以做到:

class A {
private:
int a(){printf("a");}
int b(){printf("b");}
int c(){printf("c");}
int d(){printf("d");}
public:
using func = int (A::*)();
A();
~A();
char choice;
private:
func foo();
};
A::func A::foo() {
switch(choice) {
case 'a' :
return &A::a;
case 'b' :
return &A::b;
case 'c' :
return &A::c;
case 'd' :
return &A::d;
}
}

不是返回函数指针而是调用这些函数。其次,我建议使用typedefs/与成员函数类型一起使用。请注意,您没有在类定义的末尾添加分号。

您的代码中有几个错误,请编译:

#include <iostream>
class A {
private:
int (A::*get_func())();
int a() {printf("a"); return 0;}
int b() {printf("b"); return 0;}
int c() {printf("c"); return 0;}
int d() {printf("d"); return 0;}
public:
A() = default;
~A() = default;
void init(char);
char choice;
};
void A::init(char ch) {
this->choice = ch;
int (A::*func)() = get_func();
(this->*func)(); // ->* or .* is use to call member function
}
int (A::*A::get_func())() // You forget one `A::`, so define a free function.
{
switch(choice) {
case 'a' :
return &A::a; // &A:: is require for pointer on member
// due to compatibility with C
// & is not required for address of free function :/
case 'b' :
return &A::b;
case 'c' :
return &A::c;
case 'd' :
return &A::d;
}
return nullptr;
}
int main() {
A a;
a.init('b');
}

演示

为了避免奇怪和丑陋的语法,我建议使用typedef或tralling返回类型

auto get_func() -> int (A::*)();

和在类外定义

auto A::get_func() -> int (A::*)();

如果您想尝试基于继承的方法:

class A {
public:
A();
~A();
virtual int init(){ printf("a"); }
};
class B : public A {
public:
B();
~B();
int init(){ printf("b"); }
};
class C : public A {
public:
C();
~C();
int init(){ printf("c"); }
};
class D : public A {
public:
D();
~D();
int init(){ printf("d"); }
};

如果您希望基类(A(是抽象的:

class A {
public:
A();
~A();
virtual int init() = 0;
};