返回C++类中的函数指针
Return Function Pointer in C++ Class
这是我编写的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;
};
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针