函数指针问题:传递和声明
嘿,我正在尝试弄清楚函数指针以及如何传递它们/声明它们,但是我在 Button 类构造函数中传递指针并将其成员函数指针设置为传递的指针时遇到了一些麻烦。
- 当我写 Button(Func1) Button1 时,它说需要一个“;”
- 当我写 Button(Func1); 时 它说 Button 没有默认构造函数
- 当我写 Button(&Func1); 时, 它说 Func1 需要一个初始化程序
- ;当我写 Button(&Func1()) Button1; 时, 它说表达式必须是左值或函数指示符
我做错了什么?
void Func1(){std::cout << "This is a function\n";};
void Func2(){std::cout << "This is another function\n";};
class Button
{
private:
void (*Func)(void);
public:
void Activate(){ Func() ;};
Button( void (*Function)(void)){
this->Func = Function;};
};
Button(&Func1) Button1;
Button(&Func2) Button2;
Button1.Activate();
Button2.Activate();
Hey i'm trying to figure out Function pointers and how to pass them around/ declare them, but i'm having a little trouble passing a pointer in my Button class constructor and setting it's member function pointer too the passed pointer.
- when i write Button(Func1) Button1 it says expected a ';'
- when i write Button(Func1); it says no default constructor for Button
- when i write Button(&Func1); it says Func1 requires an initializer
- when i write Button(&Func1()) Button1; it says expression must be lvalue or function designator
What am i doing wrong?
void Func1(){std::cout << "This is a function\n";};
void Func2(){std::cout << "This is another function\n";};
class Button
{
private:
void (*Func)(void);
public:
void Activate(){ Func() ;};
Button( void (*Function)(void)){
this->Func = Function;};
};
Button(&Func1) Button1;
Button(&Func2) Button2;
Button1.Activate();
Button2.Activate();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此代码语法错误:
应该是:
函数指针声明:
参数中不带 void:
编辑:工作示例位于 ideone。
This code has wrong syntax:
It should be:
And function pointer declaration:
Leave without void in parameters:
Edit: Working example at ideone.
可以这样想:
使用 typedef 来使其尽可能接近通常是最简单的。例如:
可以重写为:
当/如果事情变得复杂时,这变得特别相关 - 例如,任何时候您进行一些伪函数式编程,一个函数返回指向另一个函数的指针,您几乎肯定想要使用typedef 使两者保持一致。
编辑:您还应该意识到您似乎正在尝试重新发明命令模式。您可能想看看(例如)现代 C++ 设计中命令模式的实现。
Think of it like:
It's often easiest to use typedefs to keep it as close to that as possible, too. For example:
can be rewritten as:
this becomes particularly relevant when/if things get complex -- for example, any time you do some pseudo-functional programming, with one function returning a pointer to another function, you almost certainly want to use a typedef to keep the two straight.
Edit: You should also be aware that you seem to be trying to re-invent the Command pattern. You might want to look at (for one example) the implementation of the command pattern in Modern C++ Design.