[英]C++ assign member object function to class member function
Is there a way to use an = type assignment instead of this syntax: 有没有一种方法可以使用=类型分配来代替此语法:
void triggerAttack() { adsr.triggerAttack(); }
I was hoping to do something like: 我希望做这样的事情:
void triggerAttack() = adsr.triggerAttack
std::function<void()> triggerAttack = adsr.triggerAttack
void(*triggerAttack)() = adsr.triggerAttack
but nothing compiles! 但是没有编译!
example code: 示例代码:
class LinearADSR
{
public:
void triggerAttack() { }
};
class JerobeamBlubb : public gen
{
public:
void triggerAttack() { adsr.triggerAttack(); }
protected:
LinearADSR adsr;
};
In general, a member function pointer differs from usual pointers, since it has to be used with an instance of its class. 通常,成员函数指针与通常的指针不同,因为必须将其用于其类的实例。
So change your code to this: 因此,将您的代码更改为此:
class LinearADSR
{
public:
void triggerAttack() { }
};
class JerobeamBlubb
{
public:
void (LinearADSR::*triggerAttack)();
protected:
LinearADSR adsr;
};
int main()
{
JerobeamBlubb a;
a.triggerAttack = &LinearADSR::triggerAttack;
}
About your failed attempts: 关于失败的尝试:
void triggerAttack() = adsr.triggerAttack; is invalid syntax
std::function<void()> triggerAttack = adsr.triggerAttack
fails because triggerAttack
is a member function, and not a usual function. std::function<void()> triggerAttack = adsr.triggerAttack
失败,因为triggerAttack
是成员函数,而不是通常的函数。 You need an instance of its class as I explained before. void(*triggerAttack)() = adsr.triggerAttack
fails for the same reason as above. void(*triggerAttack)() = adsr.triggerAttack
失败的原因与上述相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.